3

我正在遍历大量嵌套目录,以搜索某些扩展名的文件,例如“.foo”,使用如下代码:

namespace fs = std::filesystem;

int main(int argc, char* argv[])
{
    std::ios_base::sync_with_stdio(false);
    for (const auto& entry : fs::recursive_directory_iterator("<some directory>")) {
        if (entry.path().extension() == ".foo") {
            std::cout << entry.path().string() << std::endl;
        }
    }
}

但是,上面会抛出名称使用 unicode/宽字符的文件。我知道我可以通过在任何地方使用 wstring 来解决上面的小程序中的问题,std::wcout << entry.path().wstring() << std::endl;但我在真实程序中真正需要做的是跳过这些文件。现在我在 for 循环的主体中捕获异常并且在这种情况下什么都不做,但我想知道是否有更直接的方法。

在 Windows/Visual Studio 中,抛出的特定异常是

目标多字节代码页中不存在 Unicode 字符的映射。

如何使用标准 C++ 测试此类文件名?

4

1 回答 1

2

Unicode 字符有 values > 0x7f,所以你可以这样做:

bool is_wide = false;
for (auto ch : entry.path().wstring())
{
    if (ch > 0x7f)
    {
        is_wide = true;
        break;
    }
}

if (!is_wide)
    std::cout << entry.path().string() << std::endl;
于 2021-07-19T22:32:32.767 回答