fwrite() modifying a file in place without fflush() lead to error

120 Views Asked by At

write_test() reads file contents and write it back just in place, why would it fail without calling fflush()?

Without calling fflush(), file contents would be in a mess if the file size is several times larger than BUFFSIZE, and the while loop never ends.

#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>

void write_test(char* fname);
int main(int argc, char* argv[])
{
    write_test(argv[1]);
    return EXIT_SUCCESS;
}

#define BUFFSIZE 1024
void write_test(char* fname)
{
    FILE* filein = fopen(fname, "rb+");
    
    void *buffer=NULL;
    buffer = malloc(BUFFSIZE);
    if (buffer==NULL)return;
    
    fseeko64(filein, 0, SEEK_SET);
    while(1)
    {
        int size=fread(buffer, 1, BUFFSIZE, filein);
        
        fseeko64(filein, -size, SEEK_CUR);
        fwrite(buffer, 1, size, filein);
        if(size<BUFFSIZE) break;
        
        //fflush(filein);
    }
    free(buffer);
    fclose(filein);
}

Enviromnent:windows10 x64, gcc version 8.1.0 (x86_64-win32-seh-rev0, Built by MinGW-W64 project)

I tried to simplify the original code.

0

There are 0 best solutions below