问题描述
我正在遍历一大组嵌套目录,搜索某些扩展名的文件,例如“.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/Visual Studio 中抛出的特定异常是
目标多字节中不存在 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;