C++ File Handling

Reading from and writing to files in C++

📁 What is File Handling?

File handling in C++ allows you to read data from files and write data to files. It's essential for storing and retrieving information permanently using fstream library.


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

int main() {
    ofstream file("example.txt");
    file << "Hello File!";
    file.close();
    return 0;
}
                                    

File Operations

✍️

Writing Files

Create and write data to files

ofstream outFile("data.txt");
outFile << "Hello World!";
outFile.close();
📖

Reading Files

Read data from existing files

ifstream inFile("data.txt");
string line;
getline(inFile, line);
inFile.close();

Appending Files

Add data to end of existing files

ofstream file("data.txt", ios::app);
file << "New line!";
file.close();
🔄

Read & Write

Both read and write operations

fstream file("data.txt", ios::in | ios::out);
// Read and write operations
file.close();

🔹 Writing to Files

Writing data to files in C++ is efficiently handled using the ofstream (output file stream) class from the <fstream> library. This process involves creating a stream object, opening a file in write mode, and using the insertion operator (<<) to output data, just like writing to the console with cout. It's essential to check if the file opened successfully and to close it after operations to ensure data integrity and free system resources. This mechanism is fundamental for creating configuration files, saving user data, logging program output, and generating reports.

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

int main() {
    // Create and open file for writing
    ofstream myFile("student.txt");
    
    if (myFile.is_open()) {
        myFile << "Name: John Doe\n";
        myFile << "Age: 20\n";
        myFile << "Grade: A\n";
        myFile.close();
        cout << "File written successfully!";
    } else {
        cout << "Unable to open file";
    }
    
    return 0;
}

Output:

File written successfully!

File Contents (student.txt):
Name: John Doe
Age: 20
Grade: A

🔹 Reading from Files

Reading data from files is accomplished using the ifstream (input file stream) class, allowing programs to access and process persistent external data. Similar to reading from cin, you can use the extraction operator (>>) for formatted input or functions like getline() to read entire lines, including spaces. Proper error handling, such as checking the file's state after opening, is crucial to prevent runtime errors if a file is missing or corrupted. This capability is vital for loading saved game states, reading configuration parameters, processing datasets, and parsing text-based files.

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

int main() {
    ifstream myFile("student.txt");
    string line;
    
    if (myFile.is_open()) {
        while (getline(myFile, line)) {
            cout << line << endl;
        }
        myFile.close();
    } else {
        cout << "Unable to open file";
    }
    
    return 0;
}

Output:

Name: John Doe
Age: 20
Grade: A

🔹 File Modes

File modes dictate how streams interact with existing files and permissions. Common modes include std::ios::in for reading, std::ios::out for writing (truncating), std::ios::app for appending, and std::ios::binary for raw byte access. Combinations like in | out allow both reading and writing. Choosing the correct mode prevents data loss, ensures proper concurrency handling, and aligns with the intended file operation, whether for configuration, logging, or binary data storage.

Common File Modes:

  • ios::out - Write to file (default for ofstream)
  • ios::in - Read from file (default for ifstream)
  • ios::app - Append to end of file
  • ios::trunc - Truncate file to zero length
  • ios::binary - Open in binary mode
// Append mode example
ofstream file("log.txt", ios::app);
file << "New log entry: " << __DATE__ << endl;
file.close();

// Binary mode example
ofstream binFile("data.bin", ios::binary);
int number = 42;
binFile.write((char*)&number, sizeof(number));
binFile.close();

🧠 Test Your Knowledge

Which header file is needed for file handling in C++?