调用 std::filesystem::copy() 时可能返回哪些错误代码?

Dan*_*ver 6 c++ error-code std-filesystem

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

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

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

有谁有关于可能返回的潜在错误代码的任何资源,或者,如果我必须以困难的方式执行此操作(并手动尝试并检查不同的错误情况),我如何知道我是否有详尽的列表?

Com*_*sMS 4

文件系统库使用的系统特定错误代码可以__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
};
Run Code Online (Sandbox Code Playgroud)

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

特别是,类别将error_code值映射到error_conditions。该实现会抛出 an 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";
    }
}
Run Code Online (Sandbox Code Playgroud)

可能会留下一些错误,但是由于您几乎肯定无法为这些错误提供专门的错误处理程序,因此只需为所有您不知道的错误情况放入一个包罗万象的通用错误处理程序关心。

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