A 50-Year-Old Bug in C's File I/O: Unraveling a Legacy Mystery

2024-12-26

While improving a DOS emulator, a developer stumbled upon a seemingly trivial bug in file I/O: appending text to a file using the `echo` command produced unexpected results. Debugging revealed a flaw in how C runtime libraries handle switching between reading and writing, a flaw tracing back to the 1970s and even earlier UNIX systems. The article delves into the historical context, from early K&R C to modern C standards, exploring implementation differences across various UNIX versions and C compilers. The root cause is identified as limitations in early C libraries' handling of update mode, with variations in how different operating systems and compilers addressed these limitations. The author concludes that even today, for portable C code, an explicit `fseek` call is necessary when switching between reading and writing a file.

Development file I/O legacy bug