[Solved] fwrite append even the file position pointer is at the correct place


If you open a file for update (+) and if you do one or more read operations, you must do a positioning operation (e.g. fseek()) before you do any writes. If you do one or more write operations, you must do a positioning operation (e.g. rewind()) before you do any reads. See POSIX’s specification of fopen() for example.

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

You are doing no positioning operations between reads and writes. That, in and of itself, leads to undefined behaviour.

Assuming your implementation exhibits ‘undefined behaviour’ by not going out of its way to misbehave, after your last fread(), you will write over the next entry — or append a new entry if the last one read was at the end of the file.

  • Decide where you want the data written.
  • Seek to the correct location (use fseek(fp, 0L, SEEK_CUR) if you don’t want to move the read/write pointer).
  • Write.
  • If you’ll be reading next, do another seek — another no-op if need so be.

0

solved fwrite append even the file position pointer is at the correct place