Recursively searching for files in the computer

前端 未结 2 744
走了就别回头了
走了就别回头了 2020-12-20 03:50

I am trying to recursively search for files in the computer using WinAPI: FindFirstFile and FindNextFile

I do not understand why, but my co

相关标签:
2条回答
  • 2020-12-20 04:42

    You have to specifically exclude ''.' and '..' from your search results so as not to recurse on them.

    0 讨论(0)
  • 2020-12-20 04:43

    Each directory (except the root directory) has two entries (. and ..) at the beginning which you need to skip.

    Otherwise, you have an infinite recursion:

    • C:\*
    • C:\Program Files (x86)\*
    • C:\Program Files (x86)\.\*
    • C:\Program Files (x86)\.\.\*
    • C:\Program Files (x86)\.\.\.\*

    and so on.

    (You'll also need to check whether each entry is a file or a directory and only recurse into directories.)

    For example:

    #include <Windows.h>
    #include <iostream>
    #include <string>
    #include <vector>    
    
    void FindFile(const std::wstring &directory)
    {
        std::wstring tmp = directory + L"\\*";
        WIN32_FIND_DATAW file;
        HANDLE search_handle = FindFirstFileW(tmp.c_str(), &file);
        if (search_handle != INVALID_HANDLE_VALUE)
        {
            std::vector<std::wstring> directories;
    
            do
            {
                if (file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                {
                    if ((!lstrcmpW(file.cFileName, L".")) || (!lstrcmpW(file.cFileName, L"..")))
                        continue;
                }
    
                tmp = directory + L"\\" + std::wstring(file.cFileName);
                std::wcout << tmp << std::endl;
    
                if (file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                    directories.push_back(tmp);
            }
            while (FindNextFileW(search_handle, &file));
    
            FindClose(search_handle);
    
            for(std::vector<std::wstring>::iterator iter = directories.begin(), end = directories.end(); iter != end; ++iter)
                FindFile(*iter);
        }
    }
    
    int main()
    {
        FindFile(L"C:");
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题