【问题标题】:C++: What is the best practice of error handling (without exceptions) while reading the fileC++:读取文件时错误处理(无异常)的最佳实践是什么
【发布时间】:2016-11-10 21:36:20
【问题描述】:

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

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

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

【问题讨论】:

  • 是的:阅读你的 C++ 书籍,它向你解释了如何在读取文件时正确检查错误。

标签: c++ error-handling std fstream


【解决方案1】:

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

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

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";
    }
}

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

请注意,这些示例都没有使用异常处理:C++ iostreams 库 [大部分] 进行错误处理而不抛出异常。

【讨论】:

    猜你喜欢
    • 2013-01-13
    • 1970-01-01
    • 1970-01-01
    • 2011-09-22
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    相关资源
    最近更新 更多