Search code examples
cfwrite

fwrite() return value does not match with file size


I am using fwrite() to write data to the file in a loop. It repeats for 40 times, but during the first fwrite() last few KBs are not written to the file. Whereas the consecutive fwrite() works fine.When I run for a single chunk say,4000 bytes fwrite() returns 4000, but the file content is less than 4000 (nearly 3000 bytes). There is no error reported during perror() also. Kindly help me in this and thanks in advance.


Solution

  • fwrite doesn't write to a file. The function writes to a buffered file stream. The buffer is flushed to disk when you close the file with fclose or flush the buffer with fflush. Use the appropriate function to empty the buffer.

    The buffer is used to get a good performance. If performance is not your concern and you need the direct write to disk you can use the setbuf or setvbuf function to disable the buffer. (Thanks for comment by Barmar).