The EOF () inference of the FStream stream is a bit counterintuitive.
By common sense logic, if the end of the file is assumed, EOF () should return to true, but how does the C + + input and output stream know if it is at the end?
The original basis is: Assume that fin>> can not read the data again , only to find the end of the file, then to the end of the flow to set the flag , after the call EOF (), only return true.
If
find>>x; At this point, the file is just finished reading the last data (save it in X)
However, at this time fin.eof () is still false, because the fin flow flag eofbit is False,fin stream at this moment feel that the file has not reached the end, only when the stream is read and write fin>>x, found that there is no read and write data, at this time the flow will know to reach the end, Only then will the flag eofbit be changed to true, at which point the stream will know that the file is at the end.
that is, EOF, after reading the last data, is still false, when trying to read a data again, because the discovery of no data readable, only to know the end of the change in the flag, EOF becomes true.
Here's a sample:
ifstream fin ("d://line.txt");
Ofstream fout ("D://t_line.txt", Ios::trunc);
List<tag_point> test_list;
Tag_point test;
Whlie (!fin.eof ())
{
fin>>test.x;
fin>>test.y;
fin>>test.z;
Test_list.push_back (test);
}
Fin.close ();
At execution time, it is found that the data in Test_list is more than one row of the data in the text, that is, the last line of data in the text is written two times.
finally found a solution, now change the above code to such as the following:
#include <iostream>
#include <stdlib.h>
#include <fstream>
int main ()
{
char c = ' C ';
Ifstream FILE ("test.txt");
if (file.peek () = = EOF)
{
cout<< "File is empty" <<endl;
Exit (1);
}
while (File.peek ()! = EOF)
{
File.get (c);
cout<<c;
}
System ("pause");
return 0;
}
The main thing is to change EOF () to peek () = = EOF, in which peek () is the current pointer to the file, EOF is the end of the file, and its value is-1, so the use of such a method to solve the above EOF () problem. Such a method can also be used in read-write binary files.
Article Source: http://blog.csdn.net/shuilan0066/archive/2009/10/14/4669451.aspx
Http://hi.baidu.com/cdever/blog/item/549cb01f1fc0eecca7866985.html