gpt4 book ai didi

c++ - 在 C++ std::streams 中,失败后,如何获取失败原因?必需:线程安全且 Windows 和 Linux 通用(或至少 Msvc/Gcc)

转载 作者:行者123 更新时间:2023-11-30 02:31:59 25 4
gpt4 key购买 nike

对不起,奇怪的标题。限于 150 个字符,因此无法使用正确的句子。

假设我已执行以下操作以发现我的文件流出现问题:

std::ofstream ofs;
do_stuff_with(ofs);
// streams don't throw on error because C++ [edit: we can make them do so, but the .what()s aren't very user-friendly]
// so we have to check for failure manually
if(!ofs){
auto fail_code = errno; // threadsafe on Win/Linux
// but what goes here?
}

1) 错误:不是线程安全的

2) strerror_s:不在 GCC 中?或者是?

3) strerror_r:不在 Msvc 中?或者是?

4) #ifdef/#define/etc:讨厌,但可能是唯一的选择

我确实做了一些搜索,但没有找到“这肯定会以一种明智但略微依赖于平台的方式工作”的答案……也就是说,我觉得这“显然是一个重复的问题”,但是我找不到原来的...

最佳答案

您始终可以使用 std::system_error 抛出您自己的异常:

#include <cerrno>
#include <fstream>
#include <iostream>
#include <system_error>

int main()
{
try
{
std::ofstream foo{"/root/bar.baz"};
foo << "bla" << std::endl;
foo.close();

if(!foo)
throw std::system_error{errno, std::generic_category()};
}
catch(const std::system_error& err)
{
std::cout << "Error: " << err.code() << " - " << err.what() << std::endl;
}

return 0;
}

这将返回 Error: generic:13 - Permission denied

关于c++ - 在 C++ std::streams 中,失败后,如何获取失败原因?必需:线程安全且 Windows 和 Linux 通用(或至少 Msvc/Gcc),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36917825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com