Question:

Which of the following is the correct way to open a binary file for both reading and writing in C++?

Show Hint

Which stream class supports both directions, and which three mode flags spell out read, write, and binary?
Updated On: Jul 2, 2026
  • ofstream file("data.bin", ios::binary | ios::in);
  • ifstream file("data.bin", ios::binary | ios::out);
  • fstream file("data.bin", ios::in | ios::out | ios::binary);
  • fstream file("data.bin", ios::binary);
Show Solution
collegedunia
Verified By Collegedunia

The Correct Option is C

Solution and Explanation

Step 1: To both read and write one stream, you need the two way stream class fstream. An ofstream is output only and an ifstream is input only, so they cannot cover both directions at once.

Step 2: The mode flags must state all three needs. Reading needs ios::in, writing needs ios::out, and binary handling needs ios::binary.

Step 3: Combine the flags with the bitwise OR operator:
 fstream file("data.bin", ios::in | ios::out | ios::binary);

Step 4: Check the wrong options. Option A uses ofstream with ios::in, a mismatch. Option B uses ifstream with ios::out, also a mismatch. Option D uses fstream but only ios::binary, so it does not clearly request both in and out.

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