如何使用std::filesystem跳过/忽略名称使用宽字符的文件



我正在一大组嵌套目录中迭代,搜索某种扩展名的文件,比如"。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/wide字符。我知道我可以通过在任何地方使用wstring(即std::wcout << entry.path().wstring() << std::endl;(来解决上面的小程序中的问题,但我在实际程序中实际需要做的是跳过这些文件。现在,我正在for循环的主体中捕捉异常,在这种情况下什么也不做,但我想知道是否有更直接的方法。

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

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

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

Unicode字符的值为> 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;

最新更新