Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default write behaviour - O_TRUNC or O_APPEND?

What is the default behaviour when you open a file with access mode O_WRONLY or O_RDWR. Is the file opened in append mode or truncate mode? From the man pages:

The argument flags must include one of the following access modes: O_RDONLY, O_WRONLY, or O_RDWR.
...
In addition, zero or more file creation flags and file status flags can be bitwise-or'd in flags.

This sounds like O_APPEND and O_TRUNC flags are optional. So what does the following do?

void main ( void )
{
    int fd = open( "foo.txt", O_WRONLY );

    write( fd, "hello", 5 );

    close( fd );
}
like image 321
Jet Blue Avatar asked Jan 23 '20 20:01

Jet Blue


People also ask

When does the O_trunc behavior apply?

The O_TRUNC behavior applies only when the file is successfully opened with O_RDWR or O_WRONLY. Truncation of the file will return the [EOVERFLOW] error if the file is larger than 2 GB minus 1 byte and if the O_LARGEFILE open flag is not also specified on the open () call. (Note that open64 () sets the O_LARGEFILE open flag automatically.)

What does O_rdonly | O_wronly mean in Linux?

In other words, the combination O_RDONLY | O_WRONLY is a logical error, and certainly does not have the same meaning as O_RDWR. Linux reserves the special, nonstandard access mode 3 (binary 11) in flags to mean: check for read and write permission on the file and return a file descriptor that can't be used for reading or writing.

What if O_creat and O_TMPFILE are not specified in Flags?

If neither O_CREAT nor O_TMPFILE is specified in flags, then mode is ignored (and can thus be specified as 0, or simply omitted). The mode argument must be supplied if O_CREAT or O_TMPFILE is specified in flags; if it is not supplied, some arbitrary bytes from the stack will be applied as the file mode.


1 Answers

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.

like image 120
John Kugelman Avatar answered Sep 20 '22 20:09

John Kugelman