C++ ifstream:检查是否打开成功
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4206816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ifstream: check if opened successfully
提问by Philipp
A colleague just told me that this code:
一位同事刚刚告诉我这段代码:
std::ifstream stream(filename.c_str());
if (!stream)
{
throw std::runtime_error("..");
}
would be wrong. He said ifstream
evaluates to 0 if opening is successful. My code works, but I wanted to find the documentation but didn't see where it says how to check if opening was successful. Can you point me to it?
会错的。他说ifstream
如果打开成功则评估为0。我的代码有效,但我想找到文档,但没有看到它在哪里说明如何检查打开是否成功。你能指点一下吗?
回答by Oliver Charlesworth
operator!
is overloadedfor std::ifstream
, so you cando this.
operator!
超载的std::ifstream
,这样你就可以做到这一点。
In my opinion, though, this is a horrible abuse of operator overloading (by the standards committee). It's much more explicit what you're checking if you just do if (stream.fail())
.
不过,在我看来,这是对运算符重载的可怕滥用(标准委员会)。如果你只是这样做,你正在检查的内容会更加明确if (stream.fail())
。
回答by Greg Satir
You can make a particular stream throw an exception on any of eof/fail/bad by calling its ios::exceptions()function with the proper bitmask. So, you could rewrite the example in the initial question above as:
通过使用正确的位掩码调用其ios::exceptions()函数,您可以使特定流在任何 eof/fail/bad 上抛出异常。因此,您可以将上述初始问题中的示例重写为:
std::ifstream stream;
stream.exceptions(std::ios::failbit | std::ios::badbit);
stream.open(filename.c_str());
Here stream will throw an exception when the failbit or badbit gets set. For example if ifstream::open()fails it will set the failbit and throw an exception. Of course, this will throw an exception later if either of these bits gets set on the stream, so this rewrite is not exactly the same as the initial example. You can call
这里流将在设置 failbit 或 badbit 时抛出异常。例如,如果ifstream::open()失败,它将设置失败位并抛出异常。当然,如果这些位中的任何一个在流上设置,这将在稍后抛出异常,因此此重写与初始示例不完全相同。你可以打电话
stream.exceptions(std::ios::goodbit);
to cancel all exceptions on the stream and go back to checking for errors.
取消流上的所有异常并返回检查错误。
回答by Martin Beckett
You can also use is_open()to check if it worked, but ! is allowed (it's not checking for zero, it's a special overload of !)
您也可以使用is_open()来检查它是否有效,但是!是允许的(它不检查零,它是 !的特殊重载)
edit:
Just out of interest - why doesn't this throw an exception?
Is it just that streams were introduced before exceptions
or are we into the old C++ thing of - it's only an error not exceptional enough to be an exception.
编辑:
只是出于兴趣-为什么不抛出异常?
只是在异常之前引入了流,
还是我们进入了旧的 C++ 事物 - 这只是一个错误,不足以成为异常。
回答by Lightness Races in Orbit
Your colleague is wrong. Perhaps he's forgotten that you're not writing C.
你的同事错了。也许他忘记了你不是在写 C。
The code is spot on. It's exactlyhow you should be checking stream state.
代码是正确的。这正是您应该如何检查流状态。