» Quick Introduction to C++ » 2. Advanced » 2.3 File I/O

File I/O

In C++, std::fstream is a part of the C++ Standard Library and provides functionality for file I/O operations. It is a combination of std::ifstream (input file stream) and std::ofstream (output file stream), allowing both reading from and writing to files. std::fstream is a versatile class that provides bidirectional access to files.

#include <iostream>
#include <fstream>  // Required for file I/O operations

int main() {
    // Writing to a file
    std::ofstream outFile("example.txt"); // Create a file stream for writing

    if (outFile.is_open()) {  // Check if the file is successfully opened
        outFile << "Hello, File I/O!\n";
        outFile << "This is a second line.\n";
        outFile.close();  // Close the file when done
        std::cout << "Data written to the file.\n";
    } else {
        std::cerr << "Unable to open the file for writing.\n";
        return 1;  // Return an error code
    }

    // Reading from a file
    std::ifstream inFile("example.txt"); // Create a file stream for reading

    if (inFile.is_open()) {
        std::string line;

        // Read and display each line from the file
        while (std::getline(inFile, line)) {
            std::cout << "Read from file: " << line << std::endl;
        }

        inFile.close();
    } else {
        std::cerr << "Unable to open the file for reading.\n";
        return 1;
    }

    return 0;
}