codegurukool.com · Free coding tutorials & online compiler

Home › C++ Tutorial › C++ files

C++ files

Write and read with fstream.

Include fstream. ofstream writes, ifstream reads. Check that the file opened.

Example code

#include <iostream>
#include <fstream>
using namespace std;
int main() {
  ofstream out("data.txt");
  out << "Hello file" << endl;
  out.close();
  ifstream in("data.txt");
  string line;
  while (getline(in, line)) cout << line << endl;
  return 0;
}

Run this code in the online editor

← C++ templatesC++ date and time →