A file already containing 500 bytes is opened with fopen(path, "w+"). What happens to the existing contents?
Correct answer
A. They are discarded immediately, because w modes truncate a file that already exists
16 views
A. They are discarded immediately, because w modes truncate a file that already exists
16 views
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.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is A? Ask here and get an explanation.