File Handling with fstream (ifstream, ofstream)
C++ replaces C's raw `FILE*` pointers with modern, type-safe stream classes `<fstream>`.
What is it?
The `<fstream>` library provides stream classes for file operations: • `ofstream`: Stream class to write to files. • `ifstream`: Stream class to read from files. • `fstream`: Stream class to both read and write.
Why is it used?
Type-safe, works seamlessly with stream operators `<<` and `>>`, and automatically closes files when stream objects go out of scope via RAII.
Detailed Explanation
File Streams:
• Writing: `std::ofstream outfile("data.txt"); outfile << "Hello\n";`
• Reading: `std::ifstream infile("data.txt"); std::string line; while (std::getline(infile, line)) { ... }`
• Checking state: `if (!infile.is_open())`.
• RAII Cleanup: The destructor of `ofstream`/`ifstream` automatically calls `.close()` when leaving scope.
Syntax Structure
Syntax Blueprint
#include <fstream>
std::ofstream file("test.txt");
file << "Text\n";
Code Example
CPP Code
#include <iostream>
#include <fstream>
#include <string>
int main() {
const std::string filename = "igm_cpp_records.txt";
// 1. Writing to file using std::ofstream
{
std::ofstream outfile(filename);
if (!outfile.is_open()) {
std::cerr << "Could not open file for writing!\n";
return 1;
}
outfile << "101,Rohan Sharma,Python\n";
outfile << "102,Sneha Patil,Data Analytics\n";
outfile << "103,Amit Deshmukh,C & C++ Programming\n";
std::cout << "Records successfully written to '" << filename << "'.\n";
} // outfile closes automatically here via RAII!
// 2. Reading from file line-by-line using std::ifstream
std::cout << "\n--- Reading Records Back ---\n";
std::ifstream infile(filename);
if (infile.is_open()) {
std::string line;
while (std::getline(infile, line)) {
std::cout << "Student Record: " << line << "\n";
}
} else {
std::cerr << "Could not open file for reading!\n";
}
return 0;
}
Explanation of the Code
• `std::ofstream` opens and writes text.
• RAII scope guarantees file handle closure without manual `.close()` calls.
• `std::getline(infile, line)` streams lines until end-of-file (EOF).
Expected Output
Records successfully written to 'igm_cpp_records.txt'.
--- Reading Records Back ---
Student Record: 101,Rohan Sharma,Python
Student Record: 102,Sneha Patil,Data Analytics
Student Record: 103,Amit Deshmukh,C & C++ Programming
Real-World Application
Used across configuration loaders, game save files, and database record dumps.
Common Mistakes to Avoid
• Not checking `is_open()` before reading or writing.
• Forgetting that opening with `std::ofstream` truncates existing file contents unless `std::ios::app` mode is passed.
Quick Practice Challenge
Open a file in append mode (`std::ios::app`) and append a timestamped log entry.
Key Takeaways
• Use `ofstream` for writing and `ifstream` for reading.
• Streams close automatically via RAII destructors.
• Always verify `file.is_open()` before streaming.