In what practical case bool(std::ifstream) != std::ifstream::good()?

最后都变了- 提交于 2019-12-12 12:26:14

问题


I would like to know in what case we can have :

bool(std::ifstream) != std::ifstream::good()

The difference is that bool(std::ifstream) does not test the eof bit whereas std::ifstream::good() tests it. But practically, the eof bit is raised if one try to read something after the end of the file. But as soon as you try to do this I think that either fail or bad bit is also set.

Consequently in what case you can only raise the eof bit ?


回答1:


Simply put, whenever you encounter the end of a file without attempting to read behind it. Consider a file "one.txt" which contains exactly one single '1' character.

Example for unformatted input:

#include <iostream>
#include <fstream>

int main()
{
    using namespace std;
    char chars[255] = {0};
    ifstream f("one.txt");
    f.getline(chars, 250, 'x');
    cout << f.good() << " != " << bool(f) << endl;
    return 0;
}

0 != 1
Press any key to continue . . .

Example for formatted input:

#include <iostream>
#include <fstream>

int main()
{
    using namespace std;
    ifstream f("one.txt");
    int i; f >> i;
    cout << f.good() << " != " << bool(f) << endl;
    return 0;
}

0 != 1
Press any key to continue . . .



来源:https://stackoverflow.com/questions/16555371/in-what-practical-case-boolstdifstream-stdifstreamgood

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