Search code examples
cfile-ioiofwrite

C function fwrite() doesn't write in file


I'm trying to write structures from tempGroupFile into GroupFile. fwrite() returns 1, when writing, but actually no data is written in the file GroupFile. Function printRec() prints out the structure on the screen. data is a variable of structure. File GroupFile is empty after these operations. Code:

GWTemp = fopen(tempGroupFile, "rb");
GW = fopen(GroupFile, "wb"); 
if((GW == NULL) || (GWTemp == NULL))
{
    puts("Failed to open file.");
    fflush(stdin);
    getchar();
    return 0;
}
while(fread(&data, sizeof data, 1, GWTemp))
{
    if(fwrite(&data, sizeof data, 1, GW))
    {
        printRec(data);
    }
}

Solution

  • You need to close the file using fclose(GW) after the while loop. This makes sure all buffers are flushed so the file is written.