C++ Programming

File I/O

Master C++ programming from basics to advanced. Learn object-oriented programming, STL, memory management, and build high-performance applications.

On this page

File I/O

File I/O (Input/Output) allows programs to read from and write to files. It's essential for data persistence and working with external data.

File Streams

C++ uses streams for file operations:

  • `ifstream`: Input file stream (reading)
  • `ofstream`: Output file stream (writing)
  • `fstream`: File stream (both reading and writing)

Opening Files

Basic File Opening

1#include <fstream>
2using namespace std;
3 
4// Open for reading
5ifstream inputFile("data.txt");
6 
7// Open for writing
8ofstream outputFile("output.txt");
9 
10// Open for both
11fstream file("data.txt", ios::in | ios::out);

File Modes

1ios::in      // Open for reading
2ios::out     // Open for writing
3ios::app     // Append mode
4ios::ate     // Seek to end on open
5ios::trunc   // Truncate file (default for ofstream)
6ios::binary  // Binary mode

Checking File Open

1ifstream file("data.txt");
2if (!file.is_open()) {
3    cerr << "Cannot open file!" << endl;
4    return 1;
5}
6 
7// Or
8if (!file) {
9    cerr << "File error!" << endl;
10}

Reading from Files

Reading Line by Line

1ifstream file("data.txt");
2string line;
3 
4while (getline(file, line)) {
5    cout << line << endl;
6}

Reading Word by Word

1ifstream file("data.txt");
2string word;
3 
4while (file >> word) {
5    cout << word << " ";
6}

Reading Character by Character

1ifstream file("data.txt");
2char ch;
3 
4while (file.get(ch)) {
5    cout << ch;
6}

Reading Numbers

1ifstream file("numbers.txt");
2int num;
3 
4while (file >> num) {
5    cout << num << " ";
6}

Writing to Files

Writing Text

1ofstream file("output.txt");
2file << "Hello, World!" << endl;
3file << "Line 2" << endl;

Appending to Files

1ofstream file("output.txt", ios::app);
2file << "New line appended" << endl;

Writing Numbers

1ofstream file("numbers.txt");
2int num = 42;
3double value = 3.14;
4 
5file << num << " " << value << endl;

File Position Operations

Getting File Position

1ifstream file("data.txt");
2streampos position = file.tellg();  // Get position

Setting File Position

1file.seekg(0, ios::beg);  // Beginning
2file.seekg(0, ios::end);  // End
3file.seekg(10, ios::cur); // 10 bytes from current

File Status

Checking File State

1ifstream file("data.txt");
2 
3if (file.good()) {
4    // File is good
5}
6 
7if (file.eof()) {
8    // End of file reached
9}
10 
11if (file.fail()) {
12    // Operation failed
13}
14 
15if (file.bad()) {
16    // Serious error
17}

Clearing File State

1file.clear();  // Clear error flags

Binary File I/O

Writing Binary Data

1ofstream file("data.bin", ios::binary);
2int num = 42;
3 
4file.write(reinterpret_cast<const char*>(&num), sizeof(num));

Reading Binary Data

1ifstream file("data.bin", ios::binary);
2int num;
3 
4file.read(reinterpret_cast<char*>(&num), sizeof(num));

String Streams

String streams allow treating strings as streams:

1#include <sstream>
2using namespace std;
3 
4// String to number
5string str = "42";
6istringstream iss(str);
7int num;
8iss >> num;
9 
10// Number to string
11ostringstream oss;
12oss << 42;
13string result = oss.str();

Best Practices

  1. ✅ Always check if file opened successfully
  2. ✅ Close files explicitly (or use RAII)
  3. ✅ Use RAII for automatic file closing
  4. ✅ Handle errors gracefully
  5. ✅ Use appropriate mode (text vs binary)
  6. ✅ Check file state after operations
  7. ✅ Use `getline` for reading lines
  8. ✅ Prefer string streams for in-memory operations

Common Patterns

Pattern 1: RAII File Wrapper

1class FileReader {
2    ifstream file;
3public:
4    FileReader(const string& filename) : file(filename) {
5        if (!file.is_open()) {
6            throw runtime_error("Cannot open file");
7        }
8    }
9    ~FileReader() { file.close(); }
10    ifstream& get() { return file; }
11};

Pattern 2: Read Entire File

1string readFile(const string& filename) {
2    ifstream file(filename);
3    ostringstream buffer;
4    buffer << file.rdbuf();
5    return buffer.str();
6}

Common Mistakes

  • ❌ Not checking if file opened
  • ❌ Forgetting to close files
  • ❌ Not handling file errors
  • ❌ Using wrong file mode
  • ❌ Not checking file state
  • ❌ Mixing text and binary modes
  • ❌ Not using RAII for file management

Next Module

In Module 15, we'll learn about Concurrency and Multithreading - running multiple operations simultaneously in C++!

Hands-on Examples

Basic File Reading

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    // Create a sample file first
    {
        ofstream createFile("sample.txt");
        createFile << "Line 1: Hello, World!" << endl;
        createFile << "Line 2: C++ File I/O" << endl;
        createFile << "Line 3: Reading files" << endl;
    }
    
    cout << "=== Reading File Line by Line ===" << endl;
    ifstream file("sample.txt");
    
    if (!file.is_open()) {
        cerr << "Error: Cannot open file!" << endl;
        return 1;
    }
    
    string line;
    int lineNumber = 1;
    
    while (getline(file, line)) {
        cout << "Line " << lineNumber << ": " << line << endl;
        lineNumber++;
    }
    
    file.close();
    
    cout << "\n=== Reading File Word by Word ===" << endl;
    ifstream file2("sample.txt");
    string word;
    
    while (file2 >> word) {
        cout << word << " ";
    }
    cout << endl;
    
    file2.close();
    
    return 0;
}

Basic file reading uses ifstream. Check if file opened with is_open(). Use getline() to read line by line. Use >> operator to read word by word. Always close files when done. File automatically closes when stream object is destroyed.

Sample Output

=== Reading File Line by Line ===
Line 1: Line 1: Hello, World!
Line 2: Line 2: C++ File I/O
Line 3: Line 3: Reading files

=== Reading File Word by Word ===
Line Line Line 1: 2: 3: Hello, World! C++ File I/O Reading files