代码之家  ›  专栏  ›  技术社区  ›  xom9ikk

c++文件夹搜索

  •  0
  • xom9ikk  · 技术社区  · 7 年前

    我需要得到一个目录中的文件夹列表,但只有文件夹。不需要任何文件。仅文件夹。我使用过滤器来确定这是否是一个文件夹,但它们不起作用,所有文件和文件夹都被输出。

    string root = "D:\\*";
    cout << "Scan " << root << endl;
    std::wstring widestr = std::wstring(root.begin(), root.end());
    const wchar_t* widecstr = widestr.c_str();
    WIN32_FIND_DATAW wfd;
    HANDLE const hFind = FindFirstFileW(widecstr, &wfd);
    

    通过这种方式,我检查它是否是一个文件夹。

    if (INVALID_HANDLE_VALUE != hFind)
        if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            if (!(wfd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
    

    如何解决问题?

    2 回复  |  直到 7 年前
        1
  •  3
  •   IInspectable    7 年前

    有两种方法可以做到这一点:困难的方法和简单的方法。

    FindFirstFile FindNextFile ,根据需要筛选出目录。您将在堆栈溢出和internet的其余部分上找到大量概述这种方法的示例。

    简单的方法:使用标准 directory_iterator 类别(或 recursive_directory_iterator :

    for ( const auto& entry : directory_iterator( path( L"abc" ) ) ) {
        if ( is_directory( entry.path() ) ) {
            // Do something with the entry
            visit( entry.path() );
        }
    }
    

    您必须包括 <filesystem> 头文件,在C++17中引入。

    注: namespace std namespace std::experimental::filesystem


    1. 特别注意,没有必要过滤掉 . .. 伪目录;这些不是由目录迭代器返回的。
        2
  •  2
  •   Daniel Sęk    7 年前

    此函数将文件夹收集到给定向量中。如果您设置 为了实现这一点,它将扫描文件夹内的文件夹内的文件夹等。

    // TODO: proper error handling.
    
    void GetFolders( std::vector<std::wstring>& result, const wchar_t* path, bool recursive )
    {
        HANDLE hFind;
        WIN32_FIND_DATA data;
        std::wstring folder( path );
        folder += L"\\";
        std::wstring mask( folder );
        mask += L"*.*";
    
        hFind=FindFirstFile(mask.c_str(),&data);
        if(hFind!=INVALID_HANDLE_VALUE)
        {
            do
            {
                std::wstring    name( folder );
                name += data.cFileName;
                if ( ( data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
                     // I see you don't want FILE_ATTRIBUTE_REPARSE_POINT
                     && !( data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT ) )
                {
                    // Skip . and .. pseudo folders.
                    if ( wcscmp( data.cFileName, L"." ) != 0 && wcscmp( data.cFileName, L".." ) != 0 )
                    {
                        result.push_back( name );
                        if ( recursive )
                            // TODO: It would be wise to check for cycles!
                            GetFolders( result, name.c_str(), recursive );
                    }
                }
            } while(FindNextFile(hFind,&data));
        }
        FindClose(hFind);
    }
    

    修改自 https://stackoverflow.com/a/46511952/8666197