blink
blink

Reputation: 49

fflush required on windows but not Linux

I am unable to find a documented reason why I need the fflush at the end of the for loop in the following code on windows but not on linux. This is to xor one file with another. without the fflush on windows it seems to read only to the second position in the file I am updating and never reads any further filling the file with that character xor'd with the second file. The fflush makes it work as I expect but runs slowly. On linux the fflush makes no difference, it works either way. I am using gcc on both systems but the windows compiler does the same thing.

#include < stdio.h>  
#include < string.h>  
#include < stdlib.h>  
#include < limits.h>  

int main(int argc, char *argv[])    
{  
     FILE *pf , *kf;  
     int index, fsize, ksize, fpos;  
     unsigned char t_char, k_char, c_char;

     pf = fopen(argv[1],"rb+"); /* open the file for I/O */ 

     kf = fopen(argv[2],"rb+"); /* open key file */
     fseek(pf, 0, SEEK_END);
     fsize = ftell(pf);
     printf(" Input size = %d\n", fsize);
     rewind(pf);
     fseek(kf, 0, SEEK_END);
     ksize = ftell(kf);
     printf(" keyfile size = %d\n", ksize);
     rewind(kf);
     if (ksize < fsize) {
     printf(" Keyfile must be equal to or longer than crypt file\n");
     exit(0);
     }
       for(index=0; index<fsize; index++) {
       t_char = fgetc(pf);
       k_char = fgetc(kf);
       c_char = t_char ^ k_char;
       fseek(pf, -1, SEEK_CUR);
       fputc(c_char, pf);
       /*fflush(pf);*/
       }
     fclose(pf);  
     fclose(kf);
     return(0);

}

Upvotes: 1

Views: 173

Answers (1)

isrnick
isrnick

Reputation: 736

Quoted from: https://pubs.opengroup.org/onlinepubs/009695399/functions/fopen.html

When a file is opened with update mode ( '+' as the second or third character in the mode argument), both input and output may be performed on the associated stream. However, the application shall ensure that output is not directly followed by input without an intervening call to fflush() or to a file positioning function ( fseek(), fsetpos(), or rewind()), and input is not directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file.

So this is necessary no matter which OS you are using, according to the documentation.

However, you could use a file positioning function, instead of fflush, and see if that is faster.

Alternatively you could copy the file content to memory and do the xor operations there, and write everything back to the file once its finished.

Upvotes: 5

Related Questions