Lesson 193 +10 XP

File I/O with fstream

File I/O with fstream

C++ lets your program save data to files and read it back later. The fstream library is the doorway to working with files.

Include the right headers

The fstream library works together with the standard iostream header:

#include <iostream>
#include <fstream>
using namespace std;

Three classes, three jobs

The fstream library ships three classes for file work:

  • ofstream - creates and writes to files (output).
  • ifstream - reads from files (input).
  • fstream - a combination of both: creates, reads, and writes.

Creating and writing a file

Use ofstream and the insertion operator <<, just like cout:

ofstream MyFile("filename.txt");

MyFile << "Files can be tricky, but it is fun enough!";

MyFile.close();

Opening filename.txt for writing creates the file if it does not exist, then << pushes text into it.

Why close the file?

Calling .close() is good practice. It flushes the data to disk and cleans up memory that the file object was holding.

Reading a file

Use ifstream and the getline() function in a while loop to pull the file out line by line:

string myText;

ifstream MyReadFile("filename.txt");

while (getline(MyReadFile, myText)) {
  cout << myText << "\n";
}

MyReadFile.close();

Every call to getline() reads the next line. When the end of the file is reached, getline() returns false and the loop ends.

TL;DR

  • ofstream writes, ifstream reads, fstream does both.
  • Include <fstream> to use any of them.
  • Write with << and read line by line with getline().
  • Always call .close() when you are done with a file.