example1_writing_text_file.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include <fstream>
#include <iostream>
#include <string>

int main() {
    std::ofstream outFile("example.txt");

    if (outFile.is_open()) {
        outFile << "Hello, File!" << std::endl;
        outFile << "This is a test of file output." << std::endl;
        outFile << "Numbers can be written too: " << 42 << std::endl;

        outFile.close();
        std::cout << "File written successfully." << std::endl;
    } else {
        std::cerr << "Unable to open file for writing." << std::endl;
    }

    return 0;
}
Back to fstream