CPP Tutorial



C++ FILE HANDLING


File Handling in C++

Learn how to read from and write to files using C++ streams.

Introduction to File Streams

C++ provides file handling through fstream library which includes:

  • ifstream – For reading files
  • ofstream – For writing files
  • fstream – For both reading and writing

Writing to a File (ofstream)

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

int main() {
    ofstream outFile("example.txt");  // Open file for writing

    if (outFile.is_open()) {
        outFile << "Hello, file handling in C++!" << endl;
        outFile << "This is a new line." << endl;
        outFile.close();  // Close the file
        cout << "Data written to file successfully." << endl;
    } else {
        cout << "Unable to open file for writing." << endl;
    }
    return 0;
}
      

The code writes text to example.txt. If the file doesn't exist, it will be created.

Reading from a File (ifstream)

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

int main() {
    ifstream inFile("example.txt");  // Open file for reading
    string line;

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

This program reads example.txt line by line and prints it to the console.

Opening a File in Both Read & Write Mode (fstream)

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

int main() {
    fstream file("example.txt", ios::in | ios::out);

    if (file.is_open()) {
        file << "Adding new content!" << endl;

        file.seekg(0);  // Move read pointer to beginning

        string content;
        while (getline(file, content)) {
            cout << content << endl;
        }

        file.close();
    } else {
        cout << "Unable to open file." << endl;
    }
    return 0;
}
      

The file is opened in both read and write mode. We write new content, then read all contents.

Important Tips

  • Always check if the file is successfully opened before reading or writing.
  • Close the file after operations to free resources.
  • Use file modes such as ios::app for appending, ios::binary for binary files.
  • File handling is essential for persistent data storage in applications.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review