C++ File Input/Output

C++ provides powerful mechanisms for file input and output through the library.

Key Concepts

Example: Writing to a File

#include <iostream>
#include <fstream>

int main() {
    std::ofstream outfile("example.txt");
    outfile << "Hello, World!";
    outfile.close();
    return 0;
}

Example: Reading from a File

#include <iostream>
#include <fstream>

int main() {
    std::ifstream infile("example.txt");
    std::string line;
    while (std::getline(infile, line)) {
        std::cout << line << '\n';
    }
    infile.close();
    return 0;
}

Always remember to close files after use to free system resources!