Reputation: 63
{
FILE* f1 = fopen("C:\\num1.bin", "wb+");//it will create a new file
int A[] = { 1,3,6,28 }; //int arr
fwrite(A, sizeof(A), 1, f1); //should insert the A array to the file
}
I do see the file but even after the fwrite
, the file remains empty (0 bytes), does anyone know why?
Upvotes: 3
Views: 1339
Reputation: 21542
A couple of things:
fclose
or fflush
after writing to the file. Without this any cached/pending writes will not necessarily be actually written to the open file.fopen
. If fopen
fails for any reason it will return a NULL pointer and not a valid file pointer. Since you're writing directly to the root of the drive C:\ on a Windows platform, that's something you definitely do want to be checking for (not that you shouldn't in other cases too, but run under a regular user account that location is often write protected).Upvotes: 5
Reputation: 12058
Result of fwrite
is not required to appear in the fille immediately after it returns. That is because file operations usually work in a buffered manner, i.e. they are cached and then flushed to speed things up and improve the performance.
The content of the file will be updated after you call fclose:
fclose()
(...) Any unwritten buffered data are flushed to the OS. Any unread buffered data are discarded.
You may also explicitly flush the internal buffer without closing the file using fflush:
fflush()
For output streams (and for update streams on which the last operation was output), writes any unwritten data from the stream's buffer to the associated output device.
Upvotes: 2
Reputation: 2556
You need to close the file with fclose
Otherwise the write buffer will not (necessarily) force the file contents to be written to disk
Upvotes: 7