Question:

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
collegedunia
Verified By Collegedunia

The Correct Option is A

Solution and Explanation

Step 1: The stream is opened with the append mode flag:
 ofstream file("example.txt", ios::app);

Step 2: The ios::app flag means every write goes to the end of the file. It does not erase the existing contents. This is different from the default ofstream open, which truncates the file to empty.

Step 3: If example.txt does not exist yet, opening it in append mode still creates a fresh empty file, then writes at the end.

Step 4: So the program writes the text \( Hello \) at the end of the file when it exists, and creates the file first when it does not. Then it closes the stream cleanly.

Answer: option A.
Was this answer helpful?
0
0