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

标签 c++ wstring 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 中抛出的具体异常是

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/

相关文章:

c++ - 在另一个类中使用类函数

c++ - 这是在调用函数中重用 C++11 lambda 的合理模式吗?

c++ - 段错误错误 C++

c++ - std::wstring 导致堆内存分配崩溃

c++ - 我不知道如何使用文件系统来查找 .txt 文件 c++

c++ - 为什么 std::filesystem::file_size 位于留给实现的目录上?

c++ - 使用 SFML RenderWindow 时内存位置的 std::length_error

c++ - 访问存储在 vector 中的指针内的字符串时崩溃

c++ - 从 Wstring 转换为 CComBstr

visual-studio-2017 - VS2017 : E0135 namespace "std" has no member "filesystem"