Read mode retrieves existing data, write mode replaces a file's existing contents, and append mode adds new data after the existing contents. The critical differences are whether the program can read or write, whether existing data is preserved, and where the file pointer begins.
In file processing, a program opens a file using a particular mode. This creates a file handle, which the program uses to access the file before closing it.
| Mode | Main purpose | Effect when opened |
|---|---|---|
Read (r) | Retrieve data | The file must normally exist. Existing contents are preserved, and the file pointer begins at the start. Writing is not permitted. |
Write (w) | Store new data | If the file exists, it is truncated, meaning all existing contents are deleted. If it does not exist, it is normally created. |
Append (a) | Add data | Existing contents are preserved. New data is written at the end of the file. If the file does not exist, it is normally created. |
For example, suppose scores.txt contains Ana: 18. Opening it in write mode and storing Leo: 20 leaves only Leo: 20. Opening it in append mode and storing Leo: 20 preserves Ana's score and adds Leo's score at the end.
The common misconception is that write mode adds data to an existing file. It does not: write mode normally erases the previous contents immediately when the file is opened. Use append mode when records must be retained.
Some languages also provide combined modes such as read-and-write, but the exact syntax depends on the programming language. The core distinction between reading, overwriting, and adding remains the same.
Exam technique: For an IB question asking you to select or explain a file mode, state both the permitted operation and its effect on existing data. If tracing file-processing code, identify the opening mode before determining the file's final contents, and remember that files should be closed after processing.