仅捕获异常就可以检测所有二进制文件在C 中读取错误是否足够

Is it sufficient to only catch exceptions to detect all binary file read/write errors in C++?

本文关键字:读取 取错误 是否 就可以 捕获异常 检测 二进制文件      更新时间:2023-10-16

在下面的示例中,设置了文件异常。在Try-Catch块内部,正在使用gcout()函数验证读取数据的大小。设置异常时是否有必要测试gcount()的返回值?

#include <iostream>
#include <fstream>
int main()
{
    char buf[100];
    std::ifstream file;
    file.exceptions(std::ios_base::badbit | std::ios_base::failbit | std::ios_base::eofbit);
    try {
        file.open("file.bin", std::ios_base::in | std::ios_base::binary);
        file.read(buf, sizeof buf);
        // Is this error check redundant?
        if (file.gcount() != sizeof buf) {
            std::cout << "gcount(): Read errorn";
        }
        file.close();
    } catch (...) {
        std::cout << "Exception: Read errorn";
    }
    return 0;
}

read()完全保证 gcount() 不能等于所需的缓冲区大小的事实。您可以在A 成功 read()之后查看gcount(),以检查其实际读取的字节数量,如果抛出异常,则不是这种情况。

在您的示例中,您设定了一个例外,以便在read()的所有可能结果上都抛出了不读取整个请求大小的结果。因此,是的,在这种情况下,检查gcount()是多余的。如果到达EOF,请检查gcount()只有例外,您想知道读取了多少个字节才有意义。对于 binary 读取,除非数据是可变长度,否则您根本不知道它的大小。如果您需要处理以EOF结尾的数据,则不应在eofbit上抛出异常。仅当EOF是一个真实的错误条件时,就将异常放置(即,流的末尾的数据不完整(。

正确,流异常功能通过类型特征BitmaskTypestd::ios_base::iostate参数传递。BitMask类型支持所有位运算符:

operator&amp;,运算符|,运算符^,运算符〜,操作员&amp; =,操作员| =和操作员^= = oter^= = = bitMask类型的值,并且与相应的内置运算符具有相同的语义如果位于bitmask元素是两个的独特整数功能,则在未签名的整数上会有。