Search code examples
cstdio

Multiple `FILE`s appending to the same file


What does the POSIX and/or C standard say about multiple FILE structures in append mode which point to the same place in the file system? Specifically, each FILE will be flushed after each write to it. For example, in this code:

FILE *a = fopen("foo", "a");
FILE *b = fopen("foo", "a");
fputc('a', a);
fflush(a);
fputc('b', b);
fflush(b);
fclose(a);
fclose(b);

Will the contents of foo always be ab, or is the result indeterminate?


Solution

  • The C Standard has this language:

    7.21.5.3 The fopen function

    ...

    Opening a file with append mode (’a’ as the first character in the mode argument) causes all subsequent writes to the file to be forced to the then current end-of-file, regardless of intervening calls to the fseek function. In some implementations, opening a binary file with append mode (’b’ as the second or third character in the above list of mode argument values) may initially position the file position indicator for the stream beyond the last data written, because of null character padding.

    I think this clearly specifies that the posted code should result in the file containing ab after execution, as long as the file did not exist prior or was empty and text files do not have bizarre behavior such as automatic appending of newline markers.

    I the file was opened in binary mode instead, the contents should definitely be ab.