- A stream is a sequence of bytes flowing between a program and a source/destination (file, console, etc.)
ifstream — input file stream (reading); ofstream — output file stream (writing); fstream — both
| 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
- Which stream class is used for reading from a file?
- a) ofstream b) ifstream c) sstream d) cout
- Which open-mode flag discards existing file content when opening?
- a) ios::app b) ios::ate c) ios::trunc d) ios::binary
- Which flag is required for raw struct/class binary I/O?
- a) ios::app b) ios::ate c) ios::trunc d) ios::binary
ios::app differs from ios::ate in that:
- a) They are identical b) ios::app always appends writes to the end; ios::ate seeks to the end once, but you can then seek elsewhere c) ios::ate is for reading only d) ios::app is binary only
Self-Test Questions
- Why should you always check
if (!fout) after opening a file stream?
- What happens if you forget to call
.close() on a file stream?