CPP

File Streams in C++ - Read and Write Files


File handling in C++ is essential for working with data stored in files. C++ provides file stream classes to read from and write to files. In this guide, we'll explore how to use file streams in C++ to read and write files, and provide sample code to illustrate its usage.

Writing to a File

To write data to a file in C++, you can use the `ofstream` class. Here's an example of how to open a file and write text to it:

#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ofstream outputFile(`example.txt`);
    if (outputFile.is_open()) {
        outputFile << `Hello, World!` << endl;
        outputFile << `This is a sample file.` << endl;
        outputFile.close();
        cout << `File written successfully.` << endl;
    } else {
        cout << `Error: Unable to open the file.` << endl;
    }
    return 0;
}
    

In this example, we use an `ofstream` object to create a new file named `example.txt` and write text to it. After writing the content, we close the file using the `close()` method.

Reading from a File

To read data from a file in C++, you can use the `ifstream` class. Here's an example of how to open an existing file and read its content:

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

In this example, we use an `ifstream` object to open the `example.txt` file and read its contents line by line using `getline()`. The content is then printed to the console.

Appending to a File

You can also append data to an existing file in C++ using the `ofstream` class in append mode. Here's an example:

#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ofstream outputFile(`example.txt`, ios::app);
    if (outputFile.is_open()) {
        outputFile << `This content is appended.` << endl;
        outputFile.close();
        cout << `File appended successfully.` << endl;
    } else {
        cout << `Error: Unable to open the file.` << endl;
    }
    return 0;
}
    

In this example, we use the `ios::app` flag to open the file in append mode. This allows us to add new content to the end of the existing file without overwriting it.

Conclusion

File streams in C++ are essential for working with external data storage. You can use the `ofstream` and `ifstream` classes to write to and read from files, respectively. Understanding file handling is crucial for many real-world applications that involve data storage and retrieval.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.