Flag Meaning
ios::in Open for reading
ios::out Open for writing
ios::app Append — writes go to the end, existing content preserved
ios::ate Open and immediately seek to the end (unlike app, you CAN seek elsewhere afterward)
ios::trunc Discard existing content on open (default with ios::out)
ios::binary Open in binary mode — required for raw struct/class I/O
#include <fstream>
ofstream fout("data.txt");
fout << "Hello CSS aspirant" << endl;
fout.close();

Stream classes, laid out

Class Purpose Header
ifstream Input file stream — reading from a file <fstream>
ofstream Output file stream — writing to a file <fstream>
fstream Both input and output on the same file <fstream>
cin/cout Standard input/output streams (console) <iostream>

Files and console I/O share the same <</>> operator syntax — this uniformity is intentional, part of the stream abstraction.

Opening, writing, and always closing

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

int main()
{
    ofstream fout("notes.txt");        // opens (creates if missing) for writing
    if (!fout)                          // ALWAYS check the stream opened successfully
    {
        cout << "Failed to open file!";
        return 1;
    }
    fout << "First line" << endl;
    fout << "Second line" << endl;
    fout.close();                       // always close -- flushes buffered data to disk

    return 0;
}

Open mode flags — combining with |

ofstream fout("log.txt", ios::app);              // append, don't overwrite
fstream file("data.dat", ios::in | ios::out | ios::binary);   // combine multiple flags
Flag Meaning
ios::in Open for reading
ios::out Open for writing
ios::app Append — writes go to the end, existing content preserved
ios::ate Open and seek to end immediately (but you CAN still seek elsewhere afterward)
ios::trunc Discard existing content on open
ios::binary Binary mode — required for raw struct/class I/O

Important MCQs

  1. Which stream class is used for reading from a file?
  2. Which open-mode flag discards existing file content when opening?
  3. Which flag is required for raw struct/class binary I/O?
  4. ios::app differs from ios::ate in that:

Self-Test Questions

  1. Why should you always check if (!fout) after opening a file stream?
  2. What happens if you forget to call .close() on a file stream?