Skip to study material
← Question index

QUESTION 20

Explain append and update streams and safe transitions between reading and writing.

5 marks

Answer in brief

Update modes permit both input and output on a stream, but changing direction requires the appropriate operation.

Mode choice

r+ opens an existing file for reading and writing without initial truncation. w+ creates or truncates a readable/writable file. a+ permits reading and append writes. Choose the mode according to whether old contents must be preserved.

Direction rules

After output, use fflush or a file-positioning operation before input. After input, use a file-positioning operation before output, unless the input operation encountered end of file. These are stream rules, not merely style suggestions. An explicit successful fseek is a clear way to express a planned transition.

Record update

For a fixed-size binary file, identify the target record, seek to its start, write the replacement and check the result. A seek after reading avoids an invalid direction change. Arbitrary variable-length text replacement is harder because changing a field’s length can shift later contents.

Safer application design

For important files, validate all new data before modifying the stored version. A temporary-file-and-replace approach can reduce partial-update risks, but platform rename and durability behaviour need a deliberate design. The teaching examples use separate demonstration filenames and do not claim crash-safe database transactions.

Complexity

Appending a known record does not require searching old keys, but device costs are not specified by C. Finding a record sequentially remains O(n) record comparisons; processing or rewriting n records requires work proportional to that data.