What is the difference between text and binary mode?
Text mode may translate newlines; binary reads/writes raw bytes—use binary for non-text formats.
Master C++ file handling: fstream, ofstream, ifstream operations. Learn text/binary file operations, file pointers, error handling, serialization, and best practices.
Input & Output
Input Only
Output Only
Raw Data
Persist data beyond program lifetime with file streams. Learn opening modes, reading/writing text, binary files, and checking stream errors—skills used in logs, configs, and data pipelines.
File I/O appears in assignments, tools, and backend services. Interviewers ask about modes, RAII, and error handling.
File handling in C++ allows programs to store data permanently on disk, read existing data, and perform various file operations. It's essential for data persistence, configuration storage, and data exchange between programs.
#include <fstream>The following table compares all file stream classes in C++ with their purposes, methods, and characteristics:
| Class | Purpose | Key Methods | Use Cases |
|---|---|---|---|
| fstream | Both input and output operations | open(), close(), read(), write(), seekg(), seekp() |
Read/write operations, file updates |
| ifstream | Input operations only (reading) | open(), close(), get(), getline(), read(), eof() |
Reading configuration, data processing |
| ofstream | Output operations only (writing) | open(), close(), put(), write(), flush() |
Logging, data storage, report generation |
| File Modes | Specify how file is opened | ios::in, ios::out, ios::app, ios::binary, ios::trunc |
Control file access behavior |
| Text Files | Human-readable data | <<, >>, getline() |
Configuration files, logs, CSV data |
| Binary Files | Raw data storage | read(), write() |
Images, databases, serialized objects |
File modes determine how a file is opened and what operations are allowed. They control whether to read, write, append, create new files, or handle binary data.
// Common file mode flags:
ios::in // Open for reading (input)
ios::out // Open for writing (output)
ios::app // Append to end of file
ios::ate // Open and seek to end
ios::trunc // Truncate file if it exists
ios::binary // Open in binary mode
// Combinations:
ios::in | ios::out // Read and write
ios::out | ios::trunc // Write and truncate
ios::out | ios::app // Write and append
ios::in | ios::binary // Read binary data
ifstream in("data.txt");ofstream out("out.txt");ofstream log("log.txt", ios::app);fstream f("b.dat", ios::binary);fstream io("db.txt", ios::in|ios::out);ofstream w("x.txt", ios::trunc);Text files store data in human-readable format. C++ provides various methods for reading and writing text files using stream operators and functions.
// Writing to text file
ofstream outFile("file.txt");
outFile << "Text data" << endl;
outFile << variable << " " << anotherVar;
// Reading from text file
ifstream inFile("file.txt");
string line;
while(getline(inFile, line)) {
cout << line << endl;
}
// Reading word by word
string word;
while(inFile >> word) {
cout << word << endl;
}
ofstream o("t.txt");
o << "Hello
";ifstream i("t.txt");
string w; i>>w;string line;
while(getline(i,line))if(!i.is_open()) return 1;i.close();ofstream a("t.txt",ios::app);
a<<"More";getline() for reading entire linesBinary files store data in raw binary format, preserving exact byte representations. They're efficient for storing complex data structures, images, and serialized objects.
// Writing binary data
ofstream binFile("data.bin", ios::binary);
int data = 42;
binFile.write((char*)&data, sizeof(data));
// Reading binary data
ifstream readBin("data.bin", ios::binary);
int readData;
readBin.read((char*)&readData, sizeof(readData));
// Working with structures
struct Data {
int id;
char name[50];
double value;
};
Data d = {1, "Example", 3.14};
binFile.write((char*)&d, sizeof(d));
ofstream o("b.dat",ios::binary);
o.write((char*)&s,sizeof s);ifstream i("b.dat",ios::binary);
i.read((char*)&s,sizeof s);int n=42;
o.write((char*)&n,sizeof n);i.read(buf, n*sizeof(int));i.seekg(0,ios::end);
streampos sz=i.tellg();i.seekg(0,ios::beg);File pointers track read/write positions in files. C++ provides functions to manipulate these pointers for random access operations.
Get current position of get/put pointers.
ifstream file("data.txt");
streampos pos = file.tellg();
cout << "Current position: " << pos;
Set position of get/put pointers.
// Move to position 100
file.seekg(100);
// Move from current position
file.seekg(50, ios::cur);
// Move from end
file.seekg(-20, ios::end);
Reference points for seeking.
ios::beg // Beginning of file
ios::cur // Current position
ios::end // End of file
// Examples:
seekg(0, ios::beg); // Beginning
seekg(0, ios::end); // End
seekg(-10, ios::cur); // Back 10 bytes
streampos p = f.tellg();f.seekg(10, ios::beg);f.seekp(0, ios::end);f.seekg(4, ios::cur);f.clear();
f.seekg(0);f.seekg(-8, ios::end);ios::beg for absolute positioningios::cur for relative positioningios::end for operations from file endProper error handling is crucial for robust file operations. C++ provides several methods to detect and handle file operation errors.
// 1. Using is_open()
ifstream file("data.txt");
if (!file.is_open()) {
cerr << "Failed to open file!";
return 1;
}
// 2. Using fail()
if (file.fail()) {
cerr << "File operation failed!";
}
// 3. Using good()
while (file.good()) {
// Safe to read
}
// 4. Using eof()
while (!file.eof()) {
// Read until end of file
}
// Check stream state
if (file.rdstate() == ios::goodbit) {
// All good
}
if (file.rdstate() & ios::failbit) {
// Non-fatal error
}
if (file.rdstate() & ios::badbit) {
// Fatal error
}
// Clear error state
file.clear();
// Set exception mask
file.exceptions(ios::failbit | ios::badbit);
if (f.fail()) cerr<<"fail";while(getline(f,line)) {}
if(f.eof())if(!f) cerr<<"no file";f.clear();f.exceptions(ios::failbit);if(!f.is_open()) return 1;is_open() after opening a filegood() before read/write operationseof() after reading to detect end of fileclear() to reset error states when appropriateSerialization is the process of converting objects into a format that can be stored or transmitted. In C++, this often means writing object data to files.
o<<s.id<<" "<<s.name<<"
";i>>s.id>>s.name;o.write((char*)&rec,sizeof rec);o<<"v1
";o<<v.size(); for(auto x:v)o<<x;if(!i) throw runtime_error("bad");ofstream f("x.txt");
// missing closeofstream f("x.txt");
// closes at }ifstream i("nope.txt");
i>>x;if(!i.is_open()) return;f<< structObj;f.write((char*)&obj,sizeof obj);Text mode may translate newlines; binary reads/writes raw bytes—use binary for non-text formats.
Destructors close automatically—close early only if you must reopen the same stream object.
Use stringstream with rdbuf(), or read line by line for large files to save memory.