1. Home
  2. Computer Science MCQs
  3. C Programming
  4. A file already containing 500 bytes is opened with…

Added 30 Nov -0001

A file already containing 500 bytes is opened with fopen(path, "w+"). What happens to the existing contents?

  1. They are discarded immediately, because w modes truncate a file that already exists Correct answer
  2. They are preserved until the first write, which then overwrites the file from its beginning
  3. They are preserved and writes append at the end, because + implies append access
  4. The open call fails with an error, since w+ is only valid for files that do not exist

Correct answer

A. They are discarded immediately, because w modes truncate a file that already exists

16 views

MCQSEXAM

Explanation

fopen with "w+" truncates an existing file to zero length at open time and then permits both reading and writing with the position at the start. Reading before writing therefore yields nothing, which surprises candidates expecting update semantics. To keep the data use "r+", which fails when the file is absent, or "a+", which always appends.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is A? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C Programming MCQs

Practise all C Programming MCQs

Similar MCQs