【问题标题】:How to skip/disregard files with names that use wide characters using std::filesystem?如何使用 std::filesystem 跳过/忽略名称使用宽字符的文件?
【发布时间】:2021-07-19 18:01:06
【问题描述】:

我正在遍历大量嵌套目录以搜索某些扩展名的文件,例如“.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 &lt;&lt; entry.path().wstring() &lt;&lt; std::endl;,但我在实际程序中真正需要做的是跳过这些文件。现在我在 for 循环的主体中捕获异常并且在这种情况下什么都不做,但我想知道是否有更直接的方法。

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

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

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

【问题讨论】:

  • std::string path = std::wstring_convert&lt;std::codecvt_utf8&lt;wchar_t&gt;&gt;(). to_bytes(entry.path().wstring()); 是我用来将其转换为 UTF8 的东西。不知道如何检查它是否宽。 codecvt_utf8 在 C++17 afaik 中已弃用..
  • @Brandon "不确定如何检查它是否宽" - 检查生成的 UTF-8 字符串是否包含任何非 ASCII 字符 > 0x7F。跨度>
  • 异常实际发生在什么时候?检索条目的path()、路径的extension() 或路径的string() 时?抛出的实际异常是什么?它说什么?
  • 发生将路径转换为字符串的情况。这是在视觉工作室。我没有实际异常的文本,但它是在 Visual Studio 的缩小转换实现中抛出的,基本上说有些字符无法进行缩小 - 我认为文件名中包含东亚字符。跨度>
  • "目标多字节代码页中不存在 Unicode 字符的映射。"

标签: c++ wstring std-filesystem


【解决方案1】:

Unicode 字符的值是&gt; 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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-01
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 2018-06-23
    • 2015-02-02
    • 2014-03-01
    相关资源
    最近更新 更多