Tsallaka zuwa abun ciki
Justice Tech School

Files

ofstream writes and ifstream reads files; include <fstream>. A file closes automatically when the object goes out of scope. Check is_open() and read lines with getline.

Example
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
using namespace std;

int main() {
  {
    ofstream out("notes.txt");
    out << "first\nsecond\n";
  }
  ifstream in("notes.txt");
  string line;
  while (getline(in, line)) {
    cout << "read: " << line << endl;
  }
  in.close();
  remove("notes.txt");
}

Result

read: first
read: second

Exercise

Which class reads from a file?

 in("a.txt");

Quiz Test

When is a file stream closed?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.