仅捕获异常以检测 C++ 中的所有二进制文件 read/write 错误是否足够?
Is it sufficient to only catch exceptions to detect all binary file read/write errors in C++?
在下面的示例中,设置了文件例外。在 try-catch 块内部使用 gcout()
函数验证读取数据的大小。 return设置异常时是否需要测试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 error\n";
}
file.close();
} catch (...) {
std::cout << "Exception: Read error\n";
}
return 0;
}
正确,流异常函数传递了 std::ios_base::iostate
parameter of type trait BitmaskType
。位掩码类型支持所有按位运算符:
The bitwise operators operator&, operator|, operator^, operator~, operator&=, operator|=, and operator^= are defined for values of the bitmask type and have the same semantics as the corresponding built-in operators on unsigned integers would have if the bitmask elements were the distinct integer powers of two.
read()
抛出异常这一事实完全保证了 gcount()
不能 等于请求的缓冲区大小。您可以在 成功 read()
之后查看 gcount()
以检查它实际读取了多少字节,您知道如果抛出异常则情况并非如此。
在您的示例中,您设置了一个异常,以便在 read()
的所有可能结果上抛出未读取整个请求大小的结果。所以是的,在那种情况下,检查 gcount()
是多余的。只有在没有抛出异常的情况下到达 EOF 时检查 gcount()
才有意义,并且您想知道读取了多少字节。这对于 binary 读取没有多大意义,除非数据是可变长度的,而你根本不知道它的大小。如果你需要处理以 EOF 结尾的数据,你不应该在 eofbit
开始时抛出异常。仅当 EOF 是真正的错误条件(即流末尾的数据不完整)时才在 EOF 上抛出异常。
在下面的示例中,设置了文件例外。在 try-catch 块内部使用 gcout()
函数验证读取数据的大小。 return设置异常时是否需要测试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 error\n";
}
file.close();
} catch (...) {
std::cout << "Exception: Read error\n";
}
return 0;
}
正确,流异常函数传递了 std::ios_base::iostate
parameter of type trait BitmaskType
。位掩码类型支持所有按位运算符:
The bitwise operators operator&, operator|, operator^, operator~, operator&=, operator|=, and operator^= are defined for values of the bitmask type and have the same semantics as the corresponding built-in operators on unsigned integers would have if the bitmask elements were the distinct integer powers of two.
read()
抛出异常这一事实完全保证了 gcount()
不能 等于请求的缓冲区大小。您可以在 成功 read()
之后查看 gcount()
以检查它实际读取了多少字节,您知道如果抛出异常则情况并非如此。
在您的示例中,您设置了一个异常,以便在 read()
的所有可能结果上抛出未读取整个请求大小的结果。所以是的,在那种情况下,检查 gcount()
是多余的。只有在没有抛出异常的情况下到达 EOF 时检查 gcount()
才有意义,并且您想知道读取了多少字节。这对于 binary 读取没有多大意义,除非数据是可变长度的,而你根本不知道它的大小。如果你需要处理以 EOF 结尾的数据,你不应该在 eofbit
开始时抛出异常。仅当 EOF 是真正的错误条件(即流末尾的数据不完整)时才在 EOF 上抛出异常。