Introduction to Reading and Writing Files in CPP

9/18/2025

#Introduction Reading Writing Files in CPP

Go Back

Introduction to Reading and Writing Files in C++

Overview

Reading and writing files in C++ is a crucial part of programming when you need to store data permanently or retrieve existing data from storage. This is commonly used in applications such as text editors, configuration storage, logging systems, and data processing.

C++ provides the <fstream> library which offers three main classes:

ClassPurpose
ifstreamRead data from files (input)
ofstreamWrite data to files (output)
fstreamRead and write data from/to files

You must include the <fstream> header to use these classes.

#include <fstream>

 #Introduction  Reading  Writing Files in CPP

Example: Writing to a File

This example demonstrates how to create and write data to a file named "data.txt".

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

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

    if (outFile.is_open()) {
        outFile << "Hello, this is a sample text." << endl;
        outFile << "C++ makes file handling easy!" << endl;
        outFile.close();
        cout << "Data written to file successfully." << endl;
    } else {
        cout << "Error opening file for writing." << endl;
    }
    return 0;
}

Output (data.txt):

Hello, this is a sample text.
C++ makes file handling easy!

Example: Reading from a File

This example shows how to read data from the "data.txt" file created earlier.

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

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

    if (inFile.is_open()) {
        cout << "Reading from file:\n";
        while (getline(inFile, line)) {
            cout << line << endl;
        }
        inFile.close();
    } else {
        cout << "Error opening file for reading." << endl;
    }
    return 0;
}

Sample Output:

Reading from file:
Hello, this is a sample text.
C++ makes file handling easy!

Tips for File Handling

  • Always call close() to close the file after operations.

  • Check is_open() before reading or writing.

  • Use getline() for line-by-line reading.

  • Combine file open modes like ios::in | ios::out when needed.


Conclusion

Reading and writing files in C++ is simple and powerful with the fstream library. Mastering these operations allows developers to create applications that can store and retrieve data efficiently from the file system.