tags:

views:

27

answers:

1

Hello, I want to open a file for both writing and reading, but after I read from it I can't write:

f_prefs = fopen(prefs_path, "r+");
while (fscanf(f_prefs, "%[^\n]\n", line) == 1)
{
    ... do some stuff ...
    fprintf(f_prefs, "test"); // doesn't work
    ...
}

Any ideas?

+3  A: 

There has to be a file positioning operation between each switch in direction - from read to write or from write to read. In case of doubt, use fseek(fp, 0, SEEK_CUR);, which seeks zero bytes from the current position. Note that you would need two fseek() operations in the loop!

C99 §7.19.5.3 The fopen() function

When a file is opened with update mode ('+' as the second or third character in the above list of mode argument values), both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of- file.

Jonathan Leffler
Wow, I didn't know that, thanks!
Claudiu