簡體   English   中英

在C ++中的所有目錄中查找所有文件

[英]Find all files in all directories in c++

我正在嘗試查找所有目錄中的所有文件,但是我不知道如何處理子目錄。 在這段代碼中,代碼看起來遍歷所有子目錄,但我不知道如何跳回。 有誰知道如何做到這一點?

__declspec(dllexport) void GetFiles(char* filedir, char* path)
{
    string s[1000];
    string path2 = path;
    UINT index = 0;

    WIN32_FIND_DATA ffd;
    TCHAR szDir[MAX_PATH];
    HANDLE hFind = INVALID_HANDLE_VALUE;
    DWORD dwError=0;

    StringCchCopy(szDir, MAX_PATH, filedir);

    if (INVALID_HANDLE_VALUE == hFind) 
        return;

    do
    {

        DWORD attributes = ffd.dwFileAttributes;

        if (attributes & FILE_ATTRIBUTE_HIDDEN)
            continue;
        else if (attributes & FILE_ATTRIBUTE_DIRECTORY)
        {
            TCHAR dir2[MAX_PATH];
            path2 = path;
            path2 += ffd.cFileName;
            path2 += "\\*";
            StringCchCopy(dir2, MAX_PATH, path2.c_str());
            SetCurrentDirectory(dir2);
        }
        else
        {
            s[index] = path;
            s[index] += ffd.cFileName;
            index++;
        }
    }
    while (FindNextFile(hFind, &ffd) >= 0); // needs to jump back if zero

    FindClose(hFind);
}

編輯:函數具有混淆編譯器的相同名稱

我認為最簡單的方法是執行遞歸函數。

這大致類似於“ c”偽代碼中的內容

void GetFiles( char*** file_path_table, char* dir )
{
   char **file_paths;
   file_paths = getAllFiles( dir );
   foreach( path in file_paths )
   {
       if ( is_directory( path ) )
       {
           GetFiles( file_path_table, path );
       }
       else
       {
           add_file_to_table( file_path_table, path );
       }
   }
}

代替通過SetCurrentDirectory()更改目錄,請對GetFiles()進行遞歸調用。 這將要求調用者傳遞對要存儲文件列表的數組(或std::vector<std::string> )的引用,而不是使用本地數組s

在舊帖子中進行一些搜索,我想我已經提到過多次進行廣度優先搜索,但是從未真正發布過代碼來展示如何做。 我想我也應該這樣做。

#include <windows.h>
#include <queue>
#include <string>
#include <iostream>

// I think MS's names for some things are obnoxious.
const HANDLE HNULL = INVALID_HANDLE_VALUE;
const int A_DIR = FILE_ATTRIBUTE_DIRECTORY;

// We'll process a file by printing its path/name
void process(std::string const &path, WIN32_FIND_DATA const &file) { 
    std::cout << path << file.cFileName << "\n";
}

void find_file(std::string const &folder_name, std::string const &fmask) {
    HANDLE finder;          // for FindFirstFile
    WIN32_FIND_DATA file;   // data about current file.
    std::priority_queue<std::string, std::vector<std::string>,
                       std::greater<std::string> > dirs;
    dirs.push(folder_name); // start with passed directory 

    do {
        std::string path = dirs.top();// retrieve directory to search
        dirs.pop();

        if (path[path.size()-1] != '\\')  // normalize the name.
            path += "\\";

        std::string mask = path + fmask;    // create mask for searching

        // traverse a directory. Search for sub-dirs separately, because we 
        // don't want a mask to apply to directory names. "*.cpp" should find
        // "a\b.cpp", even though "a" doesn't match "*.cpp".
        //
        // First search for files:
        if (HNULL==(finder=FindFirstFile(mask.c_str(), &file))) 
            continue;

        do { 
            if (!(file.dwFileAttributes & A_DIR))
                process(path, file);
        } while (FindNextFile(finder, &file));
        FindClose(finder);

        // Then search for subdirectories:
        if (HNULL==(finder=FindFirstFile((path + "*").c_str(), &file)))
            continue;
        do { 
            if ((file.dwFileAttributes & A_DIR) && (file.cFileName[0] != '.'))
                dirs.push(path + file.cFileName);
        } while (FindNextFile(finder, &file));
        FindClose(finder);
    } while (!dirs.empty());
}

int main(int argc, char **argv) { 
    if (argc > 2)
        find_file(argv[1], argv[2]);
    else
        find_file("C:\\", "*");
    return 0;
}

為什么不使用boost recursive_directory_iterator呢

注意:未經測試(但應該看起來像這樣)。

namespace bfs = boost::filesystem;

std::vector<std::string>    filenames;

std::copy(bfs::recursive_directory_iterator("<path>"),
          bfs::recursive_directory_iterator(),
          std::back_inserter(filenames)
         );

我來看看boost的目錄迭代器。

http://www.boost.org/doc/libs/1_51_0/libs/filesystem/doc/index.htm

有一些示例涵蓋了您要嘗試執行的操作,並且幾乎可以在您能想到的任何操作系統上使用。

請看示例3。它顯示了如何遍歷目錄的所有內容。 如果找到一個以前從未見過的新目錄,則只需對它進行同樣的操作。 有測試可以告訴您該文件是否是常規文件,目錄等,因此請嘗試一下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM