Geek Slack

Learn C++
    About Lesson


    C++ Files


    C++ Files

    File handling in C++ allows us to work with files stored on the system. It includes reading from and writing to files using streams, which are sequences of characters that represent data sources or destinations. C++ provides classes like ifstream, ofstream, and fstream for working with input and output files.

    1. Writing to a File

    Example of writing data to a file:

    #include <iostream>
    #include <fstream>
    
    int main() {
        // Create and open a text file
        std::ofstream outputFile("output.txt");
    
        // Check if file opened successfully
        if (outputFile.is_open()) {
            // Write data to the file
            outputFile << "Hello, World!" << std::endl;
            outputFile << "This is a line of text." << std::endl;
    
            // Close the file
            outputFile.close();
            std::cout << "Data written to file successfully." << std::endl;
        } else {
            std::cerr << "Error opening the file." << std::endl;
        }
    
        return 0;
    }

    2. Reading from a File

    Example of reading data from a file:

    #include <iostream>
    #include <fstream>
    #include <string>
    
    int main() {
        // Open a text file for reading
        std::ifstream inputFile("input.txt");
    
        // Check if file opened successfully
        if (inputFile.is_open()) {
            std::string line;
    
            // Read and display each line from the file
            while (std::getline(inputFile, line)) {
                std::cout << line << std::endl;
            }
    
            // Close the file
            inputFile.close();
        } else {
            std::cerr << "Error opening the file." << std::endl;
        }
    
        return 0;
    }

    3. Appending to a File

    Example of appending data to an existing file:

    #include <iostream>
    #include <fstream>
    
    int main() {
        // Open a text file for appending
        std::ofstream outputFile("output.txt", std::ios::app);
    
        // Check if file opened successfully
        if (outputFile.is_open()) {
            // Append data to the file
            outputFile << "Additional line appended." << std::endl;
    
            // Close the file
            outputFile.close();
            std::cout << "Data appended to file successfully." << std::endl;
        } else {
            std::cerr << "Error opening the file." << std::endl;
        }
    
        return 0;
    }

    Conclusion

    C++ file handling allows manipulation of files, including writing data to files, reading data from files, and appending data to existing files. This chapter covered basic file operations using streams (ifstream, ofstream, and fstream), demonstrating how to open, write to, read from, and append to files in C++. Understanding file handling is essential for developing applications that interact with external data files.