#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char ch = 'x';
ifstream fin("test.txt");
if (fin.eof())
{
cout << "file is empty."<< endl;
return 0;
}
while (!fin.eof())
{
fin >> ch;
cout << ch;
}
return 0;
}
输出结果:
1、不存在test.txt时,循环输出x。
2、存在rest.txt,文件内容为空,输出一个x。(fin.eof()返回false,执行到fin >> ch;不能再读数据了,才到了文件的EOF;去掉fin >> ch;则无限输出x)
3、存在test.txt,文件内容为“12345”,输出123455。(至于为什么多输出一个5,理由同上)