J_mie6
J_mie6

Reputation: 720

C++11 fgetc outputs a 0 to my file when used in "r+b" mode

I'm writing some file IO primitives for an interpreter for a language, and I'm having problems with strange behaviour of fgetc.

Here is a reproducible example (at least on windows, haven't tried on linux):

FILE* f = fopen("reprod.txt", "r+b");
fputc('a', f);
fputc('a', f);

Starting with an empty reprod.txt file, this code will write two 'a's to the file. This is fine. However, the following code does something different (again starting with an empty file):

FILE* f = fopen("reprod.txt", "r+b");
fputc('a', f);
fputc('a', f);
fgetc(f);

I would have expected fgetc to return EOF here (it does not). Instead it returns 0 and an extra 0 byte is written into my file!

I've read the manual page for fgetc and it doesn't mention anything about this! For reference, I'm compiling in C++11 with g++ on Windows 10. Is there a good reason why this is happening and how can I prevent it?

Upvotes: 0

Views: 58

Answers (1)

Jacob
Jacob

Reputation: 3686

The documentation for fopen indicates that when opening a file in an update mode ("+"), a call must be made to fflush, fseek, fsetpos, or rewind after performing a write, before performing a subsequent read. Couldn't find any word on if it's defined what happens if you fail to do so. I tried comparing this fix vs. no fix in Visual Studio 2017, and it seemed to correct the unwanted behavior

Upvotes: 1

Related Questions