3
{
    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?

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
Itsik Elia
  • 43
  • 6
  • 1
    What is the value of `f1`? Why does your code not check it? And why don't you `close()` the file? From https://linux.die.net/man/3/fopen "Upon successful completion fopen(), fdopen() and freopen() return a FILE pointer. Otherwise, NULL is returned and errno is set to indicate the error." See https://stackoverflow.com/questions/503878/how-to-know-what-the-errno-means – Mawg says reinstate Monica Feb 01 '18 at 19:22

3 Answers3

7

You need to close the file with fclose

Otherwise the write buffer will not (necessarily) force the file contents to be written to disk

Grantly
  • 2,546
  • 2
  • 21
  • 31
  • 5
  • 2
    If the program does a normal exit, the file streams should be closed, so the buffers should be flushed ([C11 §7.22.4.4 The `exit` function ¶4](https://port70.net/~nsz/c/c11/n1570.html#7.22.4.4p4) and [C11 §5.1.2.2.3 Program Termination](https://port70.net/~nsz/c/c11/n1570.html#5.1.2.2.3)). – Jonathan Leffler Feb 02 '18 at 05:55
5

A couple of things:

  1. As @Grantly correctly noted above, you are missing a call to fclose or fflush after writing to the file. Without this any cached/pending writes will not necessarily be actually written to the open file.
  2. You do not check the return value of 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).
Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
2

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.

Mateusz Grzejek
  • 11,698
  • 3
  • 32
  • 49