使用 ”!” C++ 文件 input/output 操作期间的运算符

Using the "!" operator during file input/output operations in C++

我正在审查一个用 C++ 执行文件 input/output 操作的项目。 std::ios 中定义的重载 ! 运算符有一些我以前没有遇到过的用途。我知道 ! 运算符用于检查文件是否已打开。但是,我不明白为什么作者在使用istream::seekgistream::readostream::seekp、[=20之后,又通过!运算符来使用fstream对象=] 我正在检查的项目中的方法。

下面是我查看过的源代码中 add() 函数的一部分:

#include <fstream>
#include <iostream>

bool add(std::fstream &file, std::istream &input)
{
    file.seekg((id - 1) * sizeof(Person));
    /* What is the purpose of using the "operator!" below? */
    if(!file){ return false; }

    file.read(reinterpret_cast<char *>(&temp), sizeof(Person));
    /* What is the purpose of using the "operator!" below? */
    if(!file){ return false; }

    file.seekp((id - 1) * sizeof(Person));
    /* What is the purpose of using the "operator!" below? */
    if(!file){ return false; }

    file.write(reinterpret_cast<const char*>(&person), sizeof(Person));
    /* What is the purpose of using the "operator!" below? */
    if(!file){ return false; }
}

operator! 运算符的上述用法有意义吗?

! 运算符被从 std::basic_ios 派生的 类 重载(例如 std::fstream),以指示操作后是否发生错误,或者在较早的操作后尚未清除。

From cppreference:

Returns true if an error has occurred on the associated stream. Specifically, returns true if badbit or failbit is set in rdstate().

在您显示的代码示例中,! 运算符在 每次 尝试对流进行操作后调用,如果出现错误 检测到,函数中止并且 returns 一个 false 信号。 (请注意,这些 seek/read/write 操作中的 任何 可能会失败。)

所以:

Do the above uses of the operator! operator make any sense?

是的,他们有。这是很好的模范代码,在任何评论中都应该受到赞扬。