🔹 1. Streams in C++
A stream is a flow of data (input/output).
Used for cin (input), cout (output), and file handling.
All stream classes are based on the base class ios.
🔹 2. Types of Streams
istream: for input (cin)
ostream: for output (cout)
iostream: for both input & output
ifstream: read from file
ofstream: write to file
fstream: read & write both
🔹 3. Steps for File Handling
1. Create stream object (ifstream, ofstream, fstream)
2. Open the file (file.open("file.txt"))
3. Read/Write
4. Close the file (file.close())
🔹 4. File Modes
Use with open() function:
ios::in – Read mode
ios::out – Write mode
ios::app – Append mode
ios::binary – Binary file mode
ios::trunc – Delete old content
ios::ate – Start at end of file
🔹 5. Basic File Programs
Write to file:
ofstream file("data.txt");
file << "Hello!";
file.close();
Read from file:
ifstream file("data.txt");
, string line;
getline(file, line);
cout << line;
file.close();
🔹 6. File Error Handling Functions
eof() – End of file
fail() – Fail to read/write
bad() – Serious error
good() – Everything is OK
🔹 7. File Pointers
Used to move around in a file.
seekg() – set input (get) position
seekp() – set output (put) position
tellg() – get input position
tellp() – get output position
🔹 8. cerr vs clog
cerr – prints error messages, no buffer, appears immediately
clog – logs info, is buffered
🔹 9. Binary File I/O
Use ios::binary mode
file.write((char*)&obj, sizeof(obj));
file.read((char*)&obj, sizeof(obj));
1. Explain the concept of stream and files with example.
In C++, a stream is a flow of data — either into the program (input) or out of the program
(output). It acts like a channel between the program and an input/output device or file.
There are two main types of streams:
Input stream: used to read data (e.g., cin)
Output stream: used to write data (e.g., cout)
C++ uses special classes to handle files:
ifstream – to read from a file
ofstream – to write to a file