【发布时间】:2013-07-25 17:46:46
【问题描述】:
std::fstream fin("emptyFile", std::fstream::in);
std::cout << fin.eof() << std::endl;
这会打印出0。所以使用eof 函数我无法检查文件是否为空。或者在读取一些数据后,我需要检查其中是否没有更多数据。
【问题讨论】:
std::fstream fin("emptyFile", std::fstream::in);
std::cout << fin.eof() << std::endl;
这会打印出0。所以使用eof 函数我无法检查文件是否为空。或者在读取一些数据后,我需要检查其中是否没有更多数据。
【问题讨论】:
有两种方法可以检查您是否“可以从文件中读取内容”:
fin >> var;)fin.seekg(0, ios_base::end);,后跟size_t len = fin.tellg();(然后使用fin.seekg(0, ios_base::beg);回到开头)但是,如果您尝试从文本文件中读取整数,则第二种方法可能不起作用 - 文件可能有 2MB 长,并且仍然不包含单个整数值,因为它都是空格和换行符等.
请注意,fin.eof() 会告诉您是否有人尝试在文件末尾之外读取。
【讨论】:
eof() 给你错误的结果,因为eofbit 尚未设置。如果您阅读了某些内容,您将通过文件末尾并设置eofbit。
避免使用eof() 并使用以下内容:
std::streampos current = fin.tellg();
fin.seekg (0, fin.end);
bool empty = !fin.tellg(); // true if empty file
fin.seekg (current, fin.beg); //restore stream position
【讨论】: