3

我似乎找不到可能传递到ec参数 for的错误代码列表std::filesystem::copy

cppreference.com 似乎表明错误代码是特定于操作系统的。
查看Microsoft 文档(因为我对 Windows 错误代码特别感兴趣,尽管我确信其他操作系统的资源对其他人会有所帮助)它看起来几乎就像是相同源文档的复制/粘贴,没有任何附加信息任何特定于 Windows 的东西。

我的猜测是错误代码将与此处列出的相同,但没有关于哪些与文件系统相关的信息,或者更具体地说是copy()功能(超出有根据的猜测)。

有没有人有任何关于可能返回的潜在错误代码的资源,或者,如果我必须以艰难的方式做到这一点(并手动尝试检查不同的错误场景),我怎么知道我是否有一个详尽的列表?

4

1 回答 1

2

文件系统库使用的系统特定错误代码可以__std_win_errorenum中找到。请注意数值如何 1:1 映射到 Win32 API 函数返回的值GetLastError

enum class __std_win_error : unsigned long {
    _Success                   = 0, // #define ERROR_SUCCESS                    0L
    _Invalid_function          = 1, // #define ERROR_INVALID_FUNCTION           1L
    _File_not_found            = 2, // #define ERROR_FILE_NOT_FOUND             2L
    _Path_not_found            = 3, // #define ERROR_PATH_NOT_FOUND             3L
    _Access_denied             = 5, // #define ERROR_ACCESS_DENIED              5L
    _Not_enough_memory         = 8, // #define ERROR_NOT_ENOUGH_MEMORY          8L
    _No_more_files             = 18, // #define ERROR_NO_MORE_FILES              18L
    _Sharing_violation         = 32, // #define ERROR_SHARING_VIOLATION          32L
    _Not_supported             = 50, // #define ERROR_NOT_SUPPORTED              50L
    _File_exists               = 80, // #define ERROR_FILE_EXISTS                80L
    _Invalid_parameter         = 87, // #define ERROR_INVALID_PARAMETER          87L
    _Insufficient_buffer       = 122, // #define ERROR_INSUFFICIENT_BUFFER        122L
    _Invalid_name              = 123, // #define ERROR_INVALID_NAME               123L
    _Directory_not_empty       = 145, // #define ERROR_DIR_NOT_EMPTY              145L
    _Already_exists            = 183, // #define ERROR_ALREADY_EXISTS             183L
    _Filename_exceeds_range    = 206, // #define ERROR_FILENAME_EXCED_RANGE       206L
    _Directory_name_is_invalid = 267, // #define ERROR_DIRECTORY                  267L
    _Max                       = ~0UL // sentinel not used by Win32
};

但是,您永远应该直接针对这些进行测试。设计的重点system_error是不必error_code直接解释系统特定的 s,而只需通过它们关联的 s 来解释它们error_category

特别是,类别将error_code值映射到error_conditions。实现抛出一个error_code,但客户端应用程序应始终检查error_conditions。与 不同error_codeerror_conditions 是可移植的,不依赖于实现细节。

因此,您应该如何处理代码中的这些类型的错误: 检查std::errc您希望以编程方式处理的值。然后检查error_code这些值:

std::error_code ec;
std::filesystem::copy("source.txt", "destination.txt", ec);
if (ec) {
    if (ec == std::errc::file_exists) {
        // special error handling for file_exists
        // [...]
    } else {
        // generic error handling for all other errors
        // that you don't specifically care about
        std::cerr << "Error: " << ec.message() << "\n";
    }
}

可能会遗留一些错误,但是由于您几乎可以肯定无论如何都无法为这些错误提供专门的错误处理程序,因此只需为您没有的所有错误情况放入一个通用错误处理程序关心。

系统错误库的原始作者之一 Chris Kohlhoff 有一个很棒的博客系列,虽然有些过时,但它解释了错误处理机制的设计和预期用途。

于 2019-11-18T10:22:17.590 回答