我想使用 C++ 标准库工具 (std::ifstream
) 从文件中读取 - 当然,如果遇到错误,我会可靠地报告错误。
显然,这绝非易事!
-
std::basic_fstream
的(std::ifstream
的模板是一个实例)默认不抛出异常。 - 您可以让一个基本的 fstream 抛出异常——但只能在构造之后,这样构造就不会失败。参见
basic_ios::exceptions()
(这是std::ifstream
的超父类(super class))。
14 年前,有人问过这个问题:
Get std::fstream failure error messages and/or exceptions
答案告诉我们:
- 不能保证抛出的异常会告诉我们错误的原因是什么(只是发生了一些错误)
- 我们无法保证在 fstream 上设置 failbit 或 badbit 时,
errno
/GetLastError()
会为我们提供非零/非成功值.
这很糟糕。另一方面,14年过去了。有什么改变吗?也就是说,对于抛出的异常或设置 errno
/GetLastError()
是否有更好的保证?如果不是,报告 std::fstream
构造错误的“最大努力”方法是什么?
(我很想问“为什么构造函数不会抛出失败,但我们先不谈这个。”
最佳答案
这是我现在能想到的最好的事情——“遮住我的屁股”以防 errno
不知何故未设置。在最坏的情况下,我正在浪费一些周期重新投入“不愉快的道路”。
// TODO: Consider checking errno here
std::filesystem::path file_path = whatever();
std::ifstream file(file_path, std::ios::binary | std::ios::ate);
try {
file.exceptions(std::ios::failbit | std::ios::badbit);
} catch (std::ios_base::failure& exception) {
if (errno == 0) {
throw;
}
throw std::system_error{ errno, std::generic_category(),
"opening file " + file_path.native());
}
关于c++ - 在今天的 C++ 中,构造 fstream 时我能否可靠地得到错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73126143/