What You'll Learn
- Read/write text files with fstream
- Binary file I/O for structs
- Parse data with stringstream
- Random access with seekg/seekp
Working with Files: Streams, Buffers & Binary I/O
C++ streams treat files, strings, and the console the same way — through a unified << / >> interface. This lesson covers text I/O, binary serialization, string parsing, and random-access file operations.
Text File I/O with fstream
ofstream writes, ifstream reads, and fstream does both. All three follow RAII — the destructor closes the file automatically, but calling .close() explicitly flushes the buffer immediately.
Use getline() for line-by-line reading and ios::app to append instead of overwrite. Always check .is_open() before writing to catch permission or path errors early.
Text File I/O
Write, read, and append text files
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
// Writing to a text file
ofstream outFile("example.txt");
if (outFile.is_open()) {
outFile << "Hello, file I/O!" << endl;
outFile << "Line 2: C++ streams are powerful" << endl;
outFile << "Line 3: score = " << 95 << endl;
outFile.close();
cout << "File written successfully" << endl;
}
// Reading the file back
ifstream inFile("example.txt");
...Binary File I/O
Binary I/O writes raw bytes — no formatting, no newlines, no conversion. It's fast and compact, perfect for structs, images, or any fixed-layout data. Open with ios::binary and use .write() / .read() with reinterpret_cast.
Common Mistake: Binary files are not portable across architectures — endianness and struct padding differ. For cross-platform data, use serialization libraries like Protocol Buffers or JSON.
Binary Records
Write and read binary structs to/from a file
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
struct Record {
int id;
double value;
char name[32];
};
int main() {
// Write binary records
vector<Record> data = {
{1, 3.14, "Alpha"},
{2, 2.71, "Beta"},
{3, 1.41, "Gamma"}
};
ofstream out("data.bin", ios::binary);
for (const auto& r : data) {
out.write(reinterpret_cast<const char*>(&r), sizeof(Record));
}
out.close();
cout << "Wrote " <<
...String Streams for Parsing
istringstream treats a string as an input stream — perfect for parsing CSV, config files, or log entries. ostringstream builds strings efficiently without repeated concatenation.
Pro Tip: ostringstream is faster than repeated string + string concatenation because it avoids intermediate allocations.
String Streams
Parse CSV data and build formatted strings
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main() {
// Parse CSV-like data with stringstream
string csvLine = "Alice,92,87,95,88";
istringstream iss(csvLine);
string name;
getline(iss, name, ',');
vector<int> scores;
string token;
while (getline(iss, token, ',')) {
scores.push_back(stoi(token));
}
cout << "Student: " << name << endl;
double sum = 0;
for (int s : scores) {
c
...Random Access with seekg / seekp
seekg (get) moves the read position; seekp (put) moves the write position. You can seek from the beginning (ios::beg), current position (ios::cur), or end (ios::end). tellg() returns the current position — seek to end and call tellg() to get file size.
File Seeking
Random access reading with seekg
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create a file with known content
ofstream out("seek_demo.txt");
out << "ABCDEFGHIJKLMNOP";
out.close();
// Random access reading
ifstream in("seek_demo.txt");
// Read from position 4
in.seekg(4);
char ch;
in.get(ch);
cout << "Char at pos 4: " << ch << endl; // E
// Jump to position 10
in.seekg(10, ios::beg);
in.get(ch);
cout << "Char at pos 10: " << ch << e
...Quick Reference
| Class | Purpose |
|---|---|
| ifstream | Read from files |
| ofstream | Write to files |
| fstream | Read and write |
| istringstream | Parse strings as input |
| ostringstream | Build strings as output |
Lesson Complete!
You can now read/write text and binary files, parse strings with streams, and navigate files with random access.
Sign up for free to track which lessons you've completed and get learning reminders.