File Handling in C++

File handling allows programs to store data permanently on disk and read it back later. Unlike variables (which are lost when the program ends), files persist after the program closes. C++ provides the <fstream> library for file operations.

File Stream Classes

ClassPurpose
ofstreamWrite to files (output file stream)
ifstreamRead from files (input file stream)
fstreamBoth read and write

Writing to a File

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

int main() {
    ofstream outFile("notes.txt");   // create/open file for writing

    if (outFile.is_open()) {
        outFile << "Hello, File!" << endl;
        outFile << "C++ File Handling is easy." << endl;
        outFile.close();
        cout << "Data written successfully." << endl;
    } else {
        cout << "Failed to open file." << endl;
    }
    return 0;
}

Output (on screen):

Data written successfully.

After running, a file named notes.txt is created containing:

Hello, File!
C++ File Handling is easy.

Reading from a File

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

int main() {
    ifstream inFile("notes.txt");
    string line;

    if (inFile.is_open()) {
        while (getline(inFile, line)) {
            cout << line << endl;
        }
        inFile.close();
    } else {
        cout << "Cannot open file." << endl;
    }
    return 0;
}

Output:

Hello, File!
C++ File Handling is easy.

Appending to a File

Opening with ios::app mode adds content to the end of an existing file without erasing it:

ofstream outFile("notes.txt", ios::app);
outFile << "New line appended." << endl;
outFile.close();

File Open Modes

ModeMeaning
ios::inOpen for reading
ios::outOpen for writing (creates/truncates)
ios::appAppend to end
ios::truncErase existing content when opening
ios::binaryOpen in binary mode
ios::ateMove to end of file on open

Reading and Writing with fstream

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

int main() {
    // Write
    fstream file("data.txt", ios::out);
    file << "Name: Alice
Age: 22
";
    file.close();

    // Read
    file.open("data.txt", ios::in);
    string line;
    while (getline(file, line)) {
        cout << line << endl;
    }
    file.close();
    return 0;
}

Output:

Name: Alice
Age: 22

Checking if File Exists

ifstream f("test.txt");
if (f.good()) {
    cout << "File exists." << endl;
} else {
    cout << "File not found." << endl;
}

Binary File Handling

Binary mode stores data in its raw binary format (not human-readable), useful for storing complex data structures:

struct Student {
    char name[20];
    int age;
    float marks;
};

// Write binary
Student s = {"Vikram", 21, 85.5};
ofstream out("student.dat", ios::binary);
out.write((char*)&s, sizeof(s));
out.close();

// Read binary
Student s2;
ifstream in("student.dat", ios::binary);
in.read((char*)&s2, sizeof(s2));
in.close();

cout << s2.name << " " << s2.age << " " << s2.marks << endl;

Output:

Vikram 21 85.5

File Position — seekg and seekp

  • seekg(pos) — Move the read pointer to position pos.
  • seekp(pos) — Move the write pointer to position pos.
  • tellg() — Returns the current read position.
  • tellp() — Returns the current write position.

Key Takeaways

  • File handling allows permanent storage and retrieval of data.
  • Use ofstream to write, ifstream to read, and fstream for both.
  • Always check if a file opened successfully before reading or writing.
  • Use ios::app to append without overwriting existing content.
  • Binary mode stores raw data and is faster for structured data like structs.

Leave a Comment

Your email address will not be published. Required fields are marked *