Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 567
Rajat Avatar asked May 17 '12 07:05

Rajat


1 Answers

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).

like image 62
Sergey Kalinichenko Avatar answered Sep 19 '22 05:09

Sergey Kalinichenko