我正在遍历大量嵌套目录以搜索某些扩展名的文件,比如“.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 中抛出的具体异常是
No mapping for the Unicode character exists in the target multi-byte code page.
如何使用标准 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;
关于c++ - 如何使用 std::filesystem 跳过/忽略名称使用宽字符的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68445073/