When reading a file, use feof () to determine whether the file is complete. When using the file, the last data will appear again, which is confusing!
Source code:
# Include <stdio. h>
# Include <stdlib. h>
Struct blockinfo
{
Int index;
Int started;
Int length;
};
Void main ()
{
Blockinfo infocontinue;
File * upload file;
Char * STR = "sqx.txt ";
Using file = fopen (STR, "WB ");
If (partition file = NULL)
{
Printf ("% s/n", "Create assist file failed! ");
}
For (INT I = 0; I <2; I ++)
{
Infocontinue. Index = I;
Infocontinue. Started = I + 10;
Infocontinue. Length = I * 10;
Fwrite (& infocontinue, sizeof (struct blockinfo), 1, using file );
}
Fclose (writable file );
File * readfile;
Readfile = fopen (STR, "R + ");
While (! Feof (readfile ))
{
Fread (& infocontinue, sizeof (struct blockinfo), 1, readfile );
Printf ("% S % d/N", "data block Index =", infocontinue. Index );
}
Fclose (readfile );
}
Output:
Data Block Index = 0
Data Block Index = 1
Data Block Index = 1 (repeated output !!!!!!)
Analysis:
1. The final data will be repeatedly output because feof returns 0 when the file end character EOF is located, and returns 1 at the next position. Then, the while loop exits. Therefore, we can simply use the while loop above to determine whether there will be duplicates.
2. When using feof (), you must first read the file and then use feof () to determine whether the file ends. That is:
While (1)
{
Fread ();
If (feof () break;
}
Code after modification:
# Include <stdio. h>
# Include <stdlib. h>
# Include <fstream>
# Include <iostream>
Using namespace STD;
Struct blockinfo
{
Int index;
Int started;
Int length;
};
Void main ()
{
Blockinfo infocontinue;
File * upload file;
Char * STR = "sqx.txt ";
Using file = fopen (STR, "WB ");
If (partition file = NULL)
{
Printf ("% s/n", "Create assist file failed! ");
}
For (INT I = 0; I <2; I ++)
{
Infocontinue. Index = I;
Infocontinue. Started = I + 10;
Infocontinue. Length = I * 10;
Fwrite (& infocontinue, sizeof (struct blockinfo), 1, using file );
}
Fclose (writable file );
File * readfile;
Readfile = fopen (STR, "R + ");
While (1)
{
Fread (& infocontinue, sizeof (struct blockinfo), 1, readfile );
If (feof (readfile ))
{
Break;
}
Printf ("% S % d/N", "data block Index =", infocontinue. Index );
}
Fclose (readfile );
}
Output:
Data Block Index = 0
Data Block Index = 1