Question:easy

What will the following C++ program do?

#include <iostream>
#include <fstream>
using namespace std;
int main() {
 ofstream file("example.txt", ios::app);
  file << "Hello ";
  file.close();
  return 0;
}

Show Hint

What does ios::app do to the write position, and does it destroy existing content?
Updated On: Jul 2, 2026
  • Appends "Hello " to the file if it exists, otherwise creates a new file
  • Creates a new file and writes "Hello "
  • Overwrites the file with "Hello "
  • Runtime error
Show Solution

The Correct Option is A

Solution and Explanation

Different angle, read the flag meaning:

Focus on the single flag $ios::app$. Break its two behaviours:
1. The write position is forced to the end of the file before each output.
2. If the file is absent, the stream creates it.

Because the position is the end and not the start, old data is kept, so nothing is overwritten. That removes option C.

Because a missing file is created rather than failing, there is no runtime error. That removes option D. Option B is only half true since it ignores the existing file case.

The full description is append when present, create when absent.
\[\boxed{\text{Appends \"Hello \" if the file exists, else creates it (option A)}}\]
Was this answer helpful?
0