#include#include int main() { std::ifstream input_file("example.txt"); if (!input_file.is_open()) { std::cerr << "Error opening file\n"; return 1; } std::string line; while (std::getline(input_file, line)) { std::cout << line << '\n'; } input_file.close(); return 0; }
#includeThis code creates a new file named "output.txt" and writes the string "Hello, world!" to it. In both examples, we used the fstream library to open the file and verify that it was successfully opened. We also closed the file using the `close()` function when we were finished accessing it.#include int main() { std::ofstream output_file("output.txt"); if (!output_file.is_open()) { std::cerr << "Error opening file\n"; return 1; } output_file << "Hello, world!\n"; output_file.close(); return 0; }