How to check if there isn't data in file to read

ぃ、小莉子 提交于 2019-12-23 20:09:55

问题


 std::fstream fin("emptyFile", std::fstream::in);
 std::cout << fin.eof() << std::endl;

This prints 0. So using eof function I can't check if file is empty. Or after reading some data I need to check if there is no more data in it.


回答1:


There are two ways to check if you "can read something" from a file:

  1. Try to read it, and if it fails, it wasn't OK... (e.g fin >> var;)
  2. Check the size of the file, using fin.seekg(0, ios_base::end); followed by size_t len = fin.tellg(); (and then move back to the beginning with fin.seekg(0, ios_base::beg);)

However, if you are trying to read an integer from a text-file, the second method may not work - the file could be 2MB long, and still not contain a single integer value, because it's all spaces and newlines, etc.

Note that fin.eof() tells you if there has been an attempt to read BEYOND the end of the file.




回答2:


eof() gives you the wrong result because eofbit is not set yet. If you read something you will pass the end of the file and eofbit will be set.

Avoid eof() and use the following:

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


来源:https://stackoverflow.com/questions/17865180/how-to-check-if-there-isnt-data-in-file-to-read

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!