Consider the following C++ code that writes to a file using ofstream. What will be the content of the file output.txt after running this program?
#include <fstream> #include <string> int main() { std::ofstream file("output.txt"); file << "Hello" << std::endl; file << "World" << std::endl; file.close(); return 0; }
Remember that std::endl inserts a newline character and flushes the stream.
The code writes "Hello" followed by a newline, then "World" followed by a newline. So the file contains two lines: "Hello" and "World".
What will be the output of this program if the file /root/secret.txt cannot be opened due to permission issues?
#include <fstream> #include <iostream> int main() { std::ofstream file("/root/secret.txt"); if (!file) { std::cout << "Failed to open file" << std::endl; } else { file << "Data" << std::endl; } return 0; }
Check how the program tests if the file stream is valid.
If the file cannot be opened, the ofstream object evaluates to false. So the program prints "Failed to open file".
The following code is supposed to write "Test" to log.txt, but the file remains empty. What is the reason?
#include <fstream> int main() { std::ofstream file; file << "Test"; file.close(); return 0; }
Check how the ofstream object is created and used.
The ofstream object was declared but never opened with a filename. Writing to it does nothing because it is not connected to any file.
What happens when you open a file with std::ofstream file("data.txt", std::ios::app); and write data to it?
Think about what append mode means for files.
Opening a file with std::ios::app means all writes go to the end of the file, preserving existing content.
Choose the code snippet that correctly opens a file named report.txt for writing using ofstream and checks if the file was opened successfully.
Check how to test if an ofstream is open and valid.
Option B correctly opens the file and checks the stream with if (!file) which tests if the stream is good. Options B and C use invalid comparisons. Option B uses is_open() which works but is less idiomatic than checking the stream state.