WeCodeAcademy

C++ File Streams

ExampleC++
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main() {
  const string path = "/tmp/wecode_cpp_demo.txt";
  {
    ofstream out(path);
    out << "alpha\n" << "beta\n" << "gamma\n";
  }  // file closed automatically at the end of the scope

  ifstream in(path);
  string line;
  int n = 0;
  while (getline(in, line)) {
    cout << ++n << ": " << line << endl;
  }
  remove(path.c_str());
  return 0;
}
Output
1: alpha
2: beta
3: gamma

File streams close themselves when they go out of scope: another benefit of RAII.

Quick check

Which class reads from a file?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.