Search code examples
cfileposixfopen

fopen multiple times in append mode


I have multiple threads attempting to log to the same file.

Each thread has a FILE * that points to the file. The FILE *s were opened in append ('a') mode and are using line buffering.

Opening multiple FILE * to the same file within the same process is implementation defined according to ANSI C.

Would anyone happen to know the implementation specific behaviour for MacOS, FreeBSD and Linux, specifically whether each FILE * will have its own line buffer, and whether there's any chance of lost or interleaved writes.


Solution

  • MacOS, FreeBSD and Linux are all POSIX systems. As such each FILE* will have its own user-space buffer (or none if you disable it), and once that buffer is flushed it will be written to the underlying file descriptor. POSIX guarantees that append opened file descriptor writes are atomic, thus no data will be lost. As long as your data isn't split across multiple flushes it won't interleave with each other either.