Lesson 210 +5 XP

<fstream> Classes Reference

<fstream> Classes Reference

Files are stream-like beasts. The <fstream> header unlocks three of them: ifstream, ofstream, and fstream.

The three file stream classes

ClassWhat it doesGood for
std::ifstreaminput file stream - reads from a filereading data
std::ofstreamoutput file stream - writes to a filewriting data
std::fstreamfile stream - both reads and writesread/write

The i in ifstream is "input", the o in ofstream is the "output", no prefix means "both".

Opening a file

#include <fstream>
#include <string>

using namespace std;

ifstream inFile;            // an empty input stream
inFile.open("data.txt");    // open it and point it at a file

Or open straight in the constructor:

ifstream inFile("data.txt");     // declare and open in one step
ofstream outFile("out.txt");

If the file doesn't exist and you open it for output, ofstream creates it. If you open a file for input that doesn't exist, the stream fails.

Closing a file

outFile.close();   // write any remaining buffered bytes, release the file

Object goes out of scope, the destructor calls close() for you automatically - but closing yourself is good hygiene.

Checking that the file opened

is_open() returns bool - true` if the stream actually has a file attached:

if (outFile.is_open()) {
    // safe to use
} else {
    cout << "Could not open the file!\n";
}

A safer habit: if (output.is_open()) is nicer` than hoping.

Also, a stream in its "bad" state behaves like a boolean false - so if (outFile) checks the whole stream (open plus no errors) at once.

Reading and writing

Use the same operators as cout and cin:

outFile << score << endl;   // write with <<
starta inFile >> score;     // read with >>

For whole lines, std::getline(inFile, line) works on file streams exactly like it does on cin.

File open modes (ios::)

The mode is a second argument to the constructor or open(). Multiple mode flags combine with | (OR):

ModeMeaning
ios::inopen for reading
ios::outopen for writing
ios::appappend - new writes go to the end of the file
ios::trunctruncate - erase existing contents when opened
ios::binarytreat the file as raw binary bytes
ios::ateseek to the end when opened

Common combos:

ofstream fout("log.txt", ios::app);                 // append, produce
fstream file("pos.txt", ios::in | ios::out);        // read + write
ofstream bin("data.bin", ios::binary);              // raw bytes

Default modes: ifstream opens as ios::in, ofstream opens as ios::out | ios::trunc.

Notes

  • Include <fstream> - not <iostream> - when the file comes in.
  • Reading/writing both set a "state"; check it before you trust results.
  • ios::app doesn't truncate; ios::out alone does by default via trunc`.
  • For binary files, ` and getline` are unsafe - exchange raw bytes differently.
  • A '

' wrote with \n - the OS may translate it to two characters (CRLF), which is normal.

TL;DR

  • ifstream reads, ofstream writes, fstream reads and writes.
  • Open with the constructor or open(), check success with is_open(), finish with close().
  • Modes: ios::in ios::out ios::app ios::trunc ios::binary.
  • Use <</>> for text, getline for whole lines, ios::binary for raw bytes.