C++ ifstream eof() 的使用
eof() 的使用方法1
ifstream.eof() 读到文件结束符时返回true。
大家可能有一个误区,认为读到文件结束符就是读到文件的最后一个字符。
其实不然,文件结束符是文件最后一个字符的下一个字符0xFF,eof() 读到文件结束符0xFF时返回true。
代码验证1
先来看看如下这段代码2:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;int main()
{char ch = 'x';ifstream fin("test.txt" );if (!fin){cout << "\nfile is not existent." << endl;system("pause");return 0;}else{while (!fin.eof()){fin.get(ch);cout << ch;}}system("pause");return 0;
}
编译并运行以上代码,
如果test.txt不存在,程序输出file is not existent.
如果test.txt为空,程序打印出一个x字符,
当test.txt中存在一字符串“abcd”且没有换行时,程序打印出“abcdd”,
代码验证2
为了详细的说明问题,我们在while循环中加入一点错误的验证处理机制3;
修改成以下代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;int main()
{char ch = 'x';ifstream fin("test.txt" );if (!fin){cout << "\nfile is not existent." << endl;system("pause");return 0;}else{while (!fin.eof()){fin.get(ch);if (fin.fail()){cout << "\nFile reading error" << endl;}cout << ch;}}system("pause");return 0;
}
由此可见在文件读取完符号 '!'之后,指针到达了文件结束符,代码 ifile>>c;读取失败。
但是并没有破坏 char c;的数据(内部肯定临时存在一个变量 char temp;)所以多输出了一个 ‘!’。
与“文件结束符是文件最后一个字符的下一个字符0xFF,eof() 读到文件结束符0xFF时返回true”结论一致。
解决方法
修改如下:
char ch = 'x'; 修改为 string s;
fin.get(ch); 修改为 fin >> s;
#include <iostream>
#include <fstream>
#include <string>
using namespace std;int main()
{//char ch = 'x';string s;ifstream fin("test.txt" );if (!fin){cout << "\nfile is not existent." << endl;system("pause");return 0;}else{while (!fin.eof()){//fin.get(ch);fin >> s;if (fin.fail()){cout << "\nFile reading error" << endl;}//cout << ch;cout << s;}}system("pause");return 0;
}
原因在于 string 和 char 的区别,具体原因待进一步探究。
参考资料
ifstream.eof() ↩︎
C/C++ ifstream之eof() ↩︎
ifstream(一)之 eof() 函数——解决读取文件最后一个数据多读一次的方法 ↩︎