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.