CPP

File Handling in C++ - Read and Write Files


File handling in C++ is essential for working with external data sources, such as reading data from files and writing data to files. C++ provides a set of file stream classes that make file I/O operations straightforward. In this guide, we'll explore the basics of file handling in C++.

Writing to a File

You can use the ofstream class to write data to a file. Here's how to write text to a file:

#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ofstream outFile(`output.txt`);    if (outFile.is_open()) {
        outFile << `Hello, World!` << endl;
        outFile.close();
        cout << `Data written to the file.` << endl;
    } else {
        cerr << `Error: Unable to open the file.` << endl;
    }    return 0;
}
    

In this example, we create an ofstream object, open the file `output.txt,` write data to it, and then close the file. If the file doesn't exist, it will be created.

Reading from a File

You can use the ifstream class to read data from a file. Here's how to read text from a file:

#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ifstream inFile(`input.txt`);    if (inFile.is_open()) {
        string line;
        while (getline(inFile, line)) {
            cout << line << endl;
        }
        inFile.close();
    } else {
        cerr << `Error: Unable to open the file.` << endl;
    }    return 0;
}
    

In this example, we create an ifstream object, open the file `input.txt,` and read its content line by line, displaying it to the console.

Appending to a File

You can use the ofstream class in append mode to add content to an existing file without overwriting its existing content:

#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ofstream outFile(`output.txt`, ios::app);    if (outFile.is_open()) {
        outFile << `Appending text to the file.` << endl;
        outFile.close();
        cout << `Data appended to the file.` << endl;
    } else {
        cerr << `Error: Unable to open the file.` << endl;
    }    return 0;
}
    

In this example, we open the file `output.txt` in append mode using the ios::app flag and then append new content to it.

Conclusion

File handling is an important part of C++ programming, enabling you to work with external data sources. As you continue your C++ journey, you'll explore more advanced file handling techniques, such as binary file I/O and error handling.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.