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 ⭐)

TEXT 📖 Display only
#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:

TEXT 📖 Display only
File opened successfully


2. Text File Reading and Writing

(1) 2.1 Reading Line by Line

Example: Counting file lines (Difficulty ⭐)

CPP
#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 ⭐⭐)

CPP
#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:



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 ⭐⭐⭐)

CPP
#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:



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 ⭐⭐⭐)

CPP
#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:

TEXT 📖 Display only
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 ⭐)

CPP
#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 ⭐⭐⭐)

TEXT 📖 Display only
#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:

TEXT 📖 Display only
Loaded 2 records

▶ Example 3: Simple File Read/Write (Difficulty ⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
(program output)

Expected output:

TEXT 📖 Display only
Hello, File!
C++ File Operations

❓ FAQ

Q Which is better — text files or binary files?
A It depends on your needs: - Need human readability → text files - Need performance/space efficiency → binary files - Need cross-platform compatibility → text files

Q How do I handle Chinese characters?
A C++ has poor Unicode support. Suggestions: - Save text files in UTF-8 encoding - Use third-party libraries (like iconv) - Or stick to English/pinyin only

Q What if a file can't be opened?
A Check with 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

  1. Basic (Difficulty ⭐): Use ofstream to write a text file (three lines of content), then use ifstream to read and display it on screen.

  2. Intermediate (Difficulty ⭐⭐): Use fstream to open a file in ios::binary mode, write an array of structs, then read and verify.

  3. Challenge (Difficulty ⭐⭐⭐): Use seekg/tellg to implement random file access. Create an "index file" that records the position of each record, supporting direct jumps to a specified record by index.



Next lesson: Regular Expressions (#42)

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏