The fopen documentation on cplusplus.com says:
For modes in which letters (or additions) are allowed (those that contain the β+β sign), the stream must be flushed (fflush) or (fseek, fsetpos, rewind) between the read operation followed by a write or write operation, and then read operations.
We can add a fflush call after fprintf to satisfy this requirement.
Here is my working code. It creates a file called example.txt and after the program exits, the contents of this file will be 000000000000n .
#include <stdio.h> int main(int argc, char **argv) { FILE * fp; int w; fp = fopen("example.txt","w"); fprintf(fp, "David Grayson"); fclose(fp); fp = fopen("example.txt","r+"); while(1) { if((w = fgetc(fp)) != EOF) { if((w = fgetc(fp)) != EOF) { fseek(fp,-2,SEEK_CUR); fprintf(fp,"0"); fflush(fp); // Necessary! } } else { break; } } fclose(fp); }
This has been tested with MinGW on Windows.
source share