如何在C++中获取文件关闭操作的错误信息?
C++标准库获取fstream关闭错误的可移植方案
C++标准库原生提供了标准的错误获取方式,完全可以实现跨平台的错误排查,不需要依赖操作系统特定API。
第一步:判断关闭操作是否失败
std::fstream继承自std::basic_ios,调用fs.close()后可以直接通过两种方式判断操作是否出错:
- 直接判断流对象的布尔值:
if (!fs)为真则说明操作失败 - 调用
fs.fail()方法:返回true则说明操作失败
第二步:获取错误原因的两种标准方案
方案1:异常捕获(完全符合C++标准,无平台依赖)
C++11起标准规定,流对象可以预先设置异常掩码,操作失败时会抛出std::ios_base::failure异常,该异常继承自std::system_error,可以直接拿到标准错误码和错误描述,是最规范的可移植写法。
示例代码:
#include <fstream> #include <iostream> #include <system_error> int main() { const char* path = "test.txt"; std::fstream fs; // 配置流在出现失败/严重错误时抛出异常 fs.exceptions(std::ios::failbit | std::ios::badbit); try { fs.open(path); fs.close(); } catch (const std::ios_base::failure& e) { std::cout << "文件关闭失败:" << e.what() << std::endl; // 标准错误码信息,可跨平台解析 std::error_code ec = e.code(); std::cout << "错误码值:" << ec.value() << std::endl; std::cout << "错误描述:" << ec.message() << std::endl; } return 0; }
方案2:状态位+errno兼容写法(无异常场景可用)
如果项目禁用了异常,也可以用流状态位配合errno获取错误,虽然C标准没有强制要求IO操作同步设置errno,但目前所有主流STL实现(GCC libstdc、Clang libc++、MSVC STL)都遵循这个约定,在Linux、Windows、macOS、BSD等平台都可以正常工作,注意要在调用close()之后立刻读取errno,不要插入其他可能修改errno的函数调用。
示例代码:
#include <fstream> #include <cstring> #include <iostream> #include <cerrno> int main() { const char* path = "test.txt"; std::fstream fs(path); fs.close(); if (fs.fail()) { std::cout << "文件关闭失败,流状态值:" << fs.rdstate() << std::endl; std::cout << "系统错误原因:" << std::strerror(errno) << std::endl; } return 0; }
内容的提问来源于stack exchange,提问作者DeltA
相关产品推荐
相关产品推荐

