0

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.

Rorschach
  • 60
  • 4
  • 3
    Because the standard [says so](https://port70.net/~nsz/c/c11/n1570.html#7.21.5.3p7). – n. m. could be an AI Mar 26 '22 at 08:27
  • 2
    The underlying reason is that stdio usually has separate buffers for input and output. `fflush()` ensures that the buffers are sychronized with the file contents. If you don't do this, the next read will read from the input buffer that contains the old file contents. – Barmar Mar 26 '22 at 08:33
  • 2
    You did a seek between read and write, but not between write and read. So apart from not repositioning the file pointer, you aren't testing that you read anything or was at EOF. *"When you switch from writing to reading, you must use an intervening call to either fflush or to a file positioning function."* – Weather Vane Mar 26 '22 at 08:34
  • Thanks, I tried to optimize thr original code by commiting fflush() out, results in lots of broken source file. – Rorschach Mar 26 '22 at 08:36

0 Answers0