C++: Advanced File Operations
Last updated: 2026-08-26
In lesson 40 we learned about exception handling.
Now, we'll dive into file operations — a core skill for persistent data in programs.
Whether it's configuration files, logs, or databases, file operations are essential.
1. File Stream Overview
(1) 1.1 Three File Stream Classes
C++ uses three classes to handle files:
| Class | Purpose |
|---|---|
std::ifstream |
Input file stream (reading files) |
std::ofstream |
Output file stream (writing files) |
std::fstream |
Input/output file stream (reading and writing) |
(2) 1.2 Opening a File
Example: Opening a file (Difficulty ⭐)
▶ Example 2: File Operation Demo (Difficulty ⭐)
#include <iostream>
#include <fstream>
int main() {
std::ifstream file("data.txt");
if (!file) {
std::cerr << "Unable to open file" << std::endl;
return 1;
}
std::cout << "File opened successfully" << std::endl;
file.close();
return 0;
}
Output:
File opened successfully
2. Text File Reading and Writing
(1) 2.1 Reading Line by Line
Example: Counting file lines (Difficulty ⭐)
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("data.txt");
std::string line;
int count = 0;
while (std::getline(file, line)) {
count++;
}
std::cout << "Number of lines: " << count << std::endl;
file.close();
return 0;
}
(2) 2.2 Formatted Reading and Writing
Example: Reading and writing a struct (Difficulty ⭐⭐)
#include <iostream>
#include <fstream>
struct Student {
char name[50];
int age;
double score;
};
int main() {
Student s = {"Zhang San", 20, 85.5};
// Write to file
std::ofstream out("student.txt");
out << s.name << std::endl;
out << s.age << std::endl;
out << s.score << std::endl;
out.close();
// Read from file
Student s2;
std::ifstream in("student.txt");
in >> s2.name >> s2.age >> s2.score;
in.close();
std::cout << "Name: " << s2.name << std::endl;
std::cout << "Age: " << s2.age << std::endl;
std::cout << "Score: " << s2.score << std::endl;
return 0;
}
⚠️ Warning:
- This approach doesn't work well for names with spaces (
>>stops at whitespace)
3. Binary Files
(1) 3.1 Why Use Binary Files?
| Comparison | Text File | Binary File |
|---|---|---|
| Readability | Human-readable | Not readable |
| Size | Larger | Small |
| Speed | Slower | Fast |
| Cross-platform | Good | Poor (endianness issues) |
(2) 3.2 Reading and Writing Binary Files
Example: Binary read/write of a struct (Difficulty ⭐⭐⭐)
#include <iostream>
#include <fstream>
struct Student {
char name[50];
int age;
double score;
};
int main() {
Student s = {"Zhang San", 20, 85.5};
// Write binary file
std::ofstream out("student.bin", std::ios::binary);
out.write(reinterpret_cast<char*>(&s), sizeof(s));
out.close();
// Read binary file
Student s2;
std::ifstream in("student.bin", std::ios::binary);
in.read(reinterpret_cast<char*>(&s2), sizeof(s2));
in.close();
std::cout << "Name: " << s2.name << std::endl;
std::cout << "Age: " << s2.age << std::endl;
std::cout << "Score: " << s2.score << std::endl;
return 0;
}
💡 Tip:
- Use
writeandreadfor binary I/O - You must specify the number of bytes (
sizeof)
4. Random Access
(1) 4.1 seekg and seekp
Random access allows you to jump to any position in a file for reading or writing.
| Function | Purpose |
|---|---|
seekg(pos) |
Set read position |
seekp(pos) |
Set write position |
tellg() |
Get current read position |
tellp() |
Get current write position |
(2) 4.2 Example: Modifying content in the middle of a file (Difficulty ⭐⭐⭐)
#include <iostream>
#include <fstream>
int main() {
std::fstream file("data.txt", std::ios::in | std::ios::out);
// Jump to the 10th byte
file.seekp(10);
// Write data (overwrite)
file << "Hello";
file.close();
return 0;
}
Output:
Hello, File!
C++ File Operations
5. File Stream State
(1) 5.1 State Flags
File streams have 4 state flags:
| Flag | Description |
|---|---|
good() |
Everything is fine |
eof() |
Reached end of file |
fail() |
Logical error (e.g. type mismatch) |
bad() |
Serious error (e.g. disk failure) |
(2) 5.2 Clearing State
Example: Handling end-of-file (Difficulty ⭐)
#include <iostream>
#include <fstream>
int main() {
std::ifstream file("data.txt");
std::string line;
while (true) {
std::getline(file, line);
if (file.eof()) {
break; // Reached end of file
}
std::cout << line << std::endl;
}
file.clear(); // Clear state to continue using
file.close();
return 0;
}
6. Practice: Simple Database
▶ Example 1: Student Record Management (Difficulty ⭐⭐⭐)
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
struct Student {
int id;
char name[50];
int age;
};
void saveStudents(const std::vectorStudent& students, const std::string& filename) {
std::ofstream file(filename, std::ios::binary);
for (const auto& s : students) {
file.write(reinterpret_cast<const char*>(&s), sizeof(s));
}
}
void loadStudents(std::vectorStudent& students, const std::string& filename) {
std::ifstream file(filename, std::ios::binary);
Student s;
while (file.read(reinterpret_cast<char*>(&s), sizeof(s))) {
students.push_back(s);
}
}
int main() {
std::vector<Student> students = {
{1, "Zhang San", 20},
{2, "Li Si", 21}
};
// Save
saveStudents(students, "students.bin");
// Load
std::vectorStudent loaded;
loadStudents(loaded, "students.bin");
std::cout << "Loaded " << loaded.size() << " records" << std::endl;
return 0;
}
Output:
Loaded 2 records
▶ Example 3: Simple File Read/Write (Difficulty ⭐)
#include <iostream>
#include <fstream>
#include <string>
int main() {
// Write to file
std::ofstream outFile("test.txt");
outFile << "Hello, File!" << std::endl;
outFile << "C++ File Operations" << std::endl;
outFile.close();
// Read from file
std::ifstream inFile("test.txt");
std::string line;
while (std::getline(inFile, line)) {
std::cout << line << std::endl;
}
inFile.close();
return 0;
}
Output:
(program output)
Expected output:
Hello, File!
C++ File Operations
❓ FAQ
if (!file), combined with exception handling.📖 Summary
| Topic | Key Points |
|---|---|
| File stream classes | ifstream/ofstream/fstream |
| Text files | << and >> operators |
| Binary files | write and read |
| Random access | seekg/seekp |
| State checking | eof()/fail()/bad() |
📝 Exercises
-
Basic (Difficulty ⭐): Use
ofstreamto write a text file (three lines of content), then useifstreamto read and display it on screen. -
Intermediate (Difficulty ⭐⭐): Use
fstreamto open a file inios::binarymode, write an array of structs, then read and verify. -
Challenge (Difficulty ⭐⭐⭐): Use
seekg/tellgto implement random file access. Create an "index file" that records the position of each record, supporting direct jumps to a specified record by index.
- File streams: ifstream for reading / ofstream for writing / fstream for both
- Open modes: in/out/app/binary/trunc
- File state checking: is_open/good/fail/eof
- Text files vs binary files: text is readable but slower
- Random access: seekg/tellg to position read/write locations
Next lesson: Regular Expressions (#42)