Default write behaviour - O_TRUNC or O_APPEND?

When using the O_WRONLY flag by itself, it opens the file for writing, retains the existing file contents, and puts the file pointer at the start of the file. Any writes overwrite existing content.

If you use lseek to reposition the file pointer, subsequent writes will occur at the repositioned offset.

This behavior contrasts with O_TRUNC which truncates the contents of the file when opened, and with O_APPEND which forces all writes to occur at the end of the file.


Neither.

  • By default the file is opened with the cursor positioned at the start. Writing overwrites the bytes at the beginning of the file.

  • O_TRUNC causes the file to be truncated if it exists.

  • O_APPEND causes writes to append to the end of the file instead of overwrite at the start. This flag is persistent. If you move the cursor elsewhere to read data it's always repositioned to the end of the file before each write.

The flags are orthogonal and are not mutually exclusive. You can even combine them if you want to initially truncate the file and ensure all later writes are always appends.