📜 ⬆️ ⬇️

fwrite / fread in windows can damage your data

Today I ran into an interesting behavior error in the functions of the standard C fwrite / fread library in windows xp (msvcrt.dll version 7.0.2600.5512). I wrote data (structures) using fwrite, and after that I immediately read the following after those written using fread. As a result, the first read structure in the file was damaged.

The solution was found to force data to be flushed to disk after writing.
Create two files with the same content "12345" and execute the following code:

#include <stdio.h>
#include <assert.h>

int main ()
{
char byte1 = 'b' ;
char byte2 = 'b' ;
FILE * f1 = fopen ( "1" , "r+b" );
FILE * f2 = fopen ( "2" , "r+b" );

assert ( f1 != NULL );
assert ( f2 != NULL );

fseek ( f1 , 1 , SEEK_SET );
fseek ( f2 , 1 , SEEK_SET );

fwrite (& byte1 , sizeof ( char ), 1 , f1 );
fread (& byte1 , sizeof ( char ), 1 , f1 );

fwrite (& byte2 , sizeof ( char ), 1 , f2 );
fflush ( f2 );
fread (& byte2 , sizeof ( char ), 1 , f2 );

fclose ( f1 );
fclose ( f2 );
return 0 ;
}


As a result, the contents of the first file are “1b? 45” (where “?” Is a random byte, I had 0x01, comrade is 'H'), the second is “1b345”. As you can see, the first file is damaged. Therefore, be careful when writing / reading with fwrite / fread.

')

Source: https://habr.com/ru/post/76042/


All Articles