C ++递归搜索具有某些扩展名的文件

时间:2019-10-25 10:28:18

标签: c++ windows winapi recursion visual-c++

我正在尝试编写一个函数来获取std::set的文件扩展名,并递归搜索具有任何扩展名的文件,并将路径写入文件:

auto get_files(_In_ const std::wstring root, // root dir of search
        _In_ const std::set<std::string> &ext, // extensions to search for)
        _Out_ std::wofstream &ret /* file to write paths to */) -> int
{
    HANDLE find = INVALID_HANDLE_VALUE;

    // check root path
    {
        LPCWSTR root_path = root.c_str();
        DWORD root_attrib = GetFileAttributesW(root_path);
        if(root_attrib == INVALID_FILE_ATTRIBUTES) return 1; // root doesn't exist
        if(!(root_attrib & FILE_ATTRIBUTE_DIRECTORY)) return 2; // root isn't a directory
    }

    LPCWSTR dir;
    WIN32_FIND_DATAW fd;

    // dir concat
    {
        std::wstring x = root.c_str();
        x.append(L"\\*");
        dir = x.c_str();
    }


    find = FindFirstFileW(dir, &fd);

    do {
        if(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) // current file is a dir
            get_files(dir, ext, ret);
        else {
            LPCWSTR current_ext = PathFindExtensionW(fd.cFileName);
            if(ext.find(current_ext) != ext.end()) {
                ret << fd.cFileName << '\n';
            }
        }
    } while (FindNextFileW(find, &fd) != 0);

    FindClose(find);

    return 0;

}

我收到以下错误:

  

E0304没有重载函数“ std :: set <_Kty,_Pr,_Alloc> :: find [带有_Kty = std :: string,_Pr = std :: less,_Alloc = std :: allocator]的实例”参数列表

和这个。

  

C2664'std :: _ Tree_const_iterator >> std :: _ Tree> :: find(const std :: basic_string,std :: allocator>&)const':无法将参数1从'const wchar_t *'转换为'const std :: basic_string,std :: allocator>&'

1 个答案:

答案 0 :(得分:0)

两个问题:

  1. using TValue = decltype(TGetter());std::set<std::string> &ext之间的类型冲突。您可以使用LPCWSTR current_ext解决E0304错误。
  2. 正如@Botje指出的那样,请注意std::set<std::wstring> &ext的工作范围。您可以卸下外部支架。

以下代码为我成功编译。请检查一下:

std::wstring x

对于第二个错误#include <shlwapi.h> #include <set> #include <fstream> auto get_files(_In_ const std::wstring root, // root dir of search _In_ const std::set<std::wstring> &ext, // extensions to search for) _Out_ std::wofstream &ret /* file to write paths to */) -> int { HANDLE find = INVALID_HANDLE_VALUE; // check root path { LPCWSTR root_path = root.c_str(); DWORD root_attrib = GetFileAttributesW(root_path); if (root_attrib == INVALID_FILE_ATTRIBUTES) return 1; // root doesn't exist if (!(root_attrib & FILE_ATTRIBUTE_DIRECTORY)) return 2; // root isn't a directory } LPCWSTR dir; WIN32_FIND_DATAW fd; // dir concat std::wstring x = root.c_str(); x.append(L"\\*"); dir = x.c_str(); find = FindFirstFileW(dir, &fd); do { if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) // current file is a dir get_files(dir, ext, ret); else { LPCWSTR current_ext = PathFindExtensionW(fd.cFileName); if (ext.find(current_ext) != ext.end()) { ret << fd.cFileName << '\n'; } } } while (FindNextFileW(find, &fd) != 0); FindClose(find); return 0; } ,我无法重现。确保将正确的代码发布给您,以重现这两个错误。