C++文件为空的判断?

来源:百度知道 编辑:UC知道 时间:2024/07/08 02:24:11
我打开一个文件后,如果正确的打开了的话,首先就是判断它是否为空(文件中没有数据),这个怎么判断啊?我的代码为:
ifstream in("file.txt");
if(in)
cerr<<"error to open";
if(该文件为空)
cout<<"该文件中没有记录!";
else
in>>n;

上面的那个条件是什么?
我是这样想的,文件一开始读就到了文件尾就说明这个文件为空,所以我最开始写的代码为:
if(in.eof())
cout<<"该文件中没有记录!";

但这样又不行,不知道是什么原因,大家帮我一下?

你可加一段程序即可:
ifstream fin("input.txt");
string s;
if(!fin)
{
cout<<"Error: can't open the file !"<<endl;
return;
}
fin>>s;
if(s.length()==0)
cout<<"Error:no contents in this file !"<<endl;

打开文件,没有开始读呢,倒
打不开文件可以if(!in)判断没有打开操作,想要读就是要in.read(BUF,多少字节)