C++:读取文件时错误处理(无异常)的最佳实践是什么

C++: What is the best practice of error handling (without exceptions) while reading the file

考虑以下示例。我打开文件并读取前 100 个字节。

std::ifstream fileRead;
fileRead.open("file.txt", std::ios::binary);
std::vector<char> buffer(100);
fileRead.read(buffer.data(), 100);

您能否建议在不使用异常的情况下读取文件时处理所有可能错误的最佳做法?

您需要知道您担心哪些错误,尤其是您想要处理并继续哪些错误,以及遇到哪些错误您想要终止。

例如,您可能遇到的一个错误:如果文件不存在(或者您没有 permissions/access)怎么办?这个检查很简单:

std::ifstream fileRead("file.txt", std::ios::binary);
if(!fileRead) {/*File doesn't exist! What do we do?*/};

如果文件没有 100 字节怎么办?

std::ifstream fileRead("file.txt", std::ios::binary);
if(!fileRead) {/*File doesn't exist! What do we do?*/}
else {
    std::vector<char> buffer(100);
    fileRead.read(buffer.data(), 100);
    if(!fileRead) {
        std::cout << "Only " << fileRead.gcount() << " bytes could be read.\n";
    }
}

仅针对您提供的代码,这些是我要为其编写错误处理的唯一错误。如果有其他代码与此示例关联,您的错误处理可能需要更广泛。

请注意,这些示例中 none 使用了异常处理:C++ iostreams 库在不抛出异常的情况下完成了 [大部分] 错误处理。