在什么实际情况下bool(std :: ifstream)!= std :: ifstream :: good()? [英] In what practical case bool(std::ifstream) != std::ifstream::good()?
问题描述
我想知道在什么情况下我们可以:
I would like to know in what case we can have :
bool(std::ifstream) != std::ifstream::good()
不同的是 bool :ifstream)
不测试 eof
位,而 std :: ifstream :: good()
测试它。但实际上,如果尝试在文件结尾之后读取某些内容,则会引发 eof
位。但是一旦你尝试这样做,我认为失败
或坏
位也被设置。
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.
因此,在什么情况下,您只能提高 eof
位?
Consequently in what case you can only raise the eof
bit ?
推荐答案
简单地说,只要遇到文件的结尾而不试图阅读。考虑一个只包含一个1字符的文件one.txt。
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.
未格式化输入的示例:
#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
按任意键继续。 。
0 != 1
Press any key to continue . . .
格式化输入示例:
#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
按任意键继续。 。 。
0 != 1
Press any key to continue . . .
这篇关于在什么实际情况下bool(std :: ifstream)!= std :: ifstream :: good()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!