Consider the following C++ code that opens a file, writes to it, and then closes it. What will be the output printed on the console?
#include <iostream> #include <fstream> int main() { std::ofstream file("test.txt"); if (!file.is_open()) { std::cout << "Failed to open file" << std::endl; return 1; } file << "Hello, file!" << std::endl; file.close(); if (file.is_open()) { std::cout << "File is still open" << std::endl; } else { std::cout << "File closed successfully" << std::endl; } return 0; }
Check what file.is_open() returns after closing the file.
After calling file.close(), the file stream is closed, so file.is_open() returns false. Therefore, the program prints "File closed successfully".
In C++, what happens if you do not explicitly call close() on an ofstream object before the program ends?
Think about what happens to objects when they go out of scope.
The ofstream destructor automatically closes the file if it is still open, so explicit close() is not always required.
Examine the following code snippet. It attempts to write "Hello" to a file but the file remains empty. What is the cause?
#include <fstream> int main() { std::ofstream file; file << "Hello"; file.open("output.txt"); file.close(); return 0; }
Check the order of operations: when is the file opened vs when is data written?
The code writes to the file stream before opening the file, so the data is not sent to any file. The file is opened only after writing, so the file remains empty.
Which of the following code snippets will cause a compilation error when trying to open a file for writing?
Consider which stream type supports writing with the << operator.
std::ifstream is for reading files and does not support writing with <<. Attempting to write causes a compilation error.
Analyze the following code. How many times is the file "log.txt" opened during execution?
#include <fstream> void writeLog() { std::ofstream file("log.txt", std::ios::app); file << "Log entry\n"; } int main() { for (int i = 0; i < 3; ++i) { writeLog(); } return 0; }
Consider how many times the function writeLog() is called and what happens inside it.
The function writeLog() opens the file each time it is called. Since it is called 3 times in the loop, the file is opened 3 times.