
fwrite / fread on windows can corrupt your data
Today I encountered an interesting behavior error in the functions of the standard C library fwrite / fread in windows xp (msvcrt.dll version 7.0.2600.5512). I wrote data (structures) using fwrite, and after that I immediately read the next ones written with fread. As a result, the first read structure in the file was damaged.
The solution was found in the forced flushing of data to disk after recording.
Create two files with the same contents “12345” and execute the following code:
As a result, the contents of the first file are “1b? 45” (where “?” Is a random byte, I had 0x01, my friend had 'H'), the second - “1b345”. As you can see, the first file is damaged. So be careful when writing / reading with fwrite / fread.
The solution was found in the forced flushing of data to disk after recording.
Create two files with the same contents “12345” and execute the following code:
#include
#include
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, my friend had 'H'), the second - “1b345”. As you can see, the first file is damaged. So be careful when writing / reading with fwrite / fread.