本文介绍了ifstream :: is_open vs ifstream :: fail?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

读取Savitch的 问题解决在中, std :: ifstream :: fail 作为示例显示,以检查文件是否正确打开( ifstream 或 ofstream )。

Reading Savitch's Problem Solving in C++, std::ifstream::fail is shown as an example to check if a file has been correctly opened (ifstream or ofstream).

ve以前使用,因为它是我第一次显示, std :: ifstream :: is_open 执行相同的检查。

I've previously used, as it is what I was first shown, std::ifstream::is_open to perform the same check.

这是更好的做法?

或者在尝试打开后直接调用任何一个的情况下,它没有实际差别吗? p>

Or in the case that either one is called directly after attempting to open, does it make no practical difference?

推荐答案

简介



std :: ifstream: :fail 包括检查 std :: ifstream :: is_open ,但 std :: ifstream :: is_open 只检查是否可以创建文件的句柄。

INTRODUCTION

std::ifstream::fail includes checking std::ifstream::is_open, but std::ifstream::is_open only checks if it was possible to create a handle to the file.

std :: ifstream :: fail 可以返回 true :ifstream :: is_open 返回 true ;它们不是互相排斥的。

std::ifstream::fail can return true, even if std::ifstream::is_open returns true; they are not the mutually exclusive.

.fail 将检查整体health >,这涉及诸如检查流当前进入了失败状态以尝试读取无效值,而 .is_open 将仅检查流是否当前附加到文件, .is_open 不在乎流是否处于失败状态,或不。

.fail will check the overall "health" of the stream, which involves things such as checking the stream has currently entered a fail state from trying to read an invalid value, whereas .is_open will only check if the stream is currently attached to a file, .is_open doesn't care if the stream is in a fail state, or not.

通常建议您依赖于以查看流是否可以读取/写入。这包括检查流的整体健康。

Normally it's recommended to rely on the explicit operator bool () to see if a stream is ready to be read/written to. This includes checking the overall health of the stream.

我们可以在 some_stream / p>

Can we make another read/write operation on some_stream?

if (some_stream) {
  // stream is alive and well
} else {
  // something is wrong
}

如果你明确想看看是否有一些 fstream 实际上附加到一个文件,使用 is_open ,如果你想检查整体健康;使用 .fail 或依赖于流可转换为 bool 的事实。

If you explicitly would like to see if some fstream is actually attached to a file, use is_open, and if you want to check the overall health; use .fail or rely on the fact that a stream is convertiable to bool.

这篇关于ifstream :: is_open vs ifstream :: fail?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 23:28