File Handling in C++: Reading and Writing Files

Explore practical examples of file handling in C++ with reading and writing files to get started easily.
By Taylor

Understanding File Handling in C++

File handling in C++ is essential for managing data outside of your program. It allows you to read from and write to files, enabling persistent storage and retrieval of information. In this guide, we’ll explore three diverse examples of file handling in C++, focusing on reading and writing files.

Example 1: Writing Data to a Text File

When you want to save information generated by your program, writing to a text file is a common use case. For instance, you might want to log user activity or save configuration settings.

#include <iostream>
#include <fstream> // Include fstream for file handling
#include <string>

int main() {
    std::ofstream outFile("example.txt"); // Create an output file stream

    if (outFile.is_open()) { // Check if the file is open
        outFile << "This is a test file.\n"; // Write to the file
        outFile << "Writing some sample text.\n";
        outFile.close(); // Close the file
        std::cout << "Data written to file successfully!" << std::endl;
    } else {
        std::cerr << "Error opening file for writing." << std::endl;
    }
    return 0;
}

Notes:

  • In this example, we use std::ofstream to create and write to a file named example.txt.
  • The is_open() method checks if the file was successfully opened before attempting to write.
  • Always remember to close the file using close() to ensure data is flushed and resources are released.

Example 2: Reading Data from a Text File

Sometimes, you need to read data from a file, such as loading user settings or reading input data for processing. This example demonstrates how to read lines from a text file.

#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream inFile("example.txt"); // Create an input file stream
    std::string line;

    if (inFile.is_open()) { // Check if the file is open
        while (getline(inFile, line)) { // Read line by line
            std::cout << line << std::endl; // Print each line to the console
        }
        inFile.close(); // Close the file
    } else {
        std::cerr << "Error opening file for reading." << std::endl;
    }
    return 0;
}

Notes:

  • Here, std::ifstream is used to read from example.txt.
  • The getline() function allows you to read the file line by line, making it easy to process text data in chunks.
  • As with writing, always check if the file is open before attempting to read.

Example 3: Appending Data to a File

Appending data to an existing file allows you to add new information without overwriting the existing contents. This is useful for logging or adding new entries to a record.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream outFile("example.txt", std::ios::app); // Open in append mode

    if (outFile.is_open()) { // Check if the file is open
        outFile << "Appending a new line to the file.\n"; // Append text
        outFile.close(); // Close the file
        std::cout << "Data appended to file successfully!" << std::endl;
    } else {
        std::cerr << "Error opening file for appending." << std::endl;
    }
    return 0;
}

Notes:

  • The std::ios::app flag is used to open the file in append mode, which means new data will be added to the end of the file.
  • Always verify if the file is open before writing to ensure your program runs smoothly.

These examples of file handling in C++: reading and writing files will help you manage data efficiently in your applications. Happy coding!