Failing to read file loaded with ifstream

馋奶兔 提交于 2019-12-02 02:31:49

If paths_in.good() keeps failing then it means that some of the stream error flags are set (badbit, eofbit or failbit).

  • eofbit - end of file was reached
  • badbit - error with the stream buffer such as memory shortage or an exception inside the stream buffer is cast
  • failbit - some other error beside eof was reached

In order to find out what happened, you need to check which errorbit is set first, and then find out more about the specific error, and what can cause it.

Out of curiosity, does this code output the contents of the file correctly? If this code works, then the problem is something else. If this code doesn't work, then that likely means that the file either isn't where you specified, or you don't have read permissions on it.

void bot_manager_item::create_games() {
    std::ifstream paths_in("C:\\Users\\bill hank\\Documents\\bot_plugins\\directory_listing.txt");

    char q[5000];
    while (paths_in.getline(q, 5000)) {
        std::cout << q << std::endl;
    }
}

This code does a few minor things differently.

  1. std::ios::in doesn't need to be explicitly specified for std::ifstream.

  2. it doesn't use is_good, while that should be fine, you can just treat the std::ifstream as a bool which will be true when it is in a good state.

  3. getline() returns a reference to the stream it operated on, so you can just put that whole line in the condition.

  4. cosmetic, but no need to explicitly close the ifstream if it is about to go out of scope.

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