fseek does not work when file is opened in "a" (append) mode

Rajat picture Rajat · May 17, 2012 · Viewed 10.2k times · Source
FILE* f = fopen("rajat", "w");
fputs("sometext", f);
fseek(f, 6, SEEK_SET);
fputs("is a", f);
fclose(f);

Successfully returns: "someteis a"

But

FILE* f = fopen("rajat", "a");
fputs("sometext", f);
fseek(f, 6, SEEK_SET);
fputs("is a", f);
fclose(f);

Does not work. Returns "sometextis a"

Any ideas why? What is the solution to this, so that the second code outputs exactly like the first?

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · May 17, 2012

When you open in append mode, the file pointer is returned to the end of file before every write. You can reposition the pointer with fseek for reading, but as soon as you call a function that writes to the file, the pointer goes back to the end of file.

Or, putting it another way, to prevent loss of data, the position of the "write pointer" overrides the position of the "read pointer". After any append, the write pointer bounces to the new EOF.

The answer at this link references the appropriate section of the C standard.

Use the "w+" mode if you would like to write to arbitrary places in file. An existing file will be overwritten.

If you would like to append to an existing file initially, but then fseek to arbitrary place, use "r+" followed by fseek(f, 0, SEEK_END).