[英]How to skip/disregard files with names that use wide characters using 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/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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.