在c ++中查找所有目录中的所有文件

时间:2012-09-24 16:09:34

标签: c++ file search find

我试图找到所有目录中的所有文件,但我不知道如何处理子目录。在这段代码中,代码看起来都是通过所有子目录,但我不知道如何跳回。有谁知道怎么做?

__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);
}

编辑:函数具有与编译器混淆的相同名称

5 个答案:

答案 0 :(得分:2)

我认为最简单的方法是做一个递归函数。

在“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 );
       }
   }
}

答案 1 :(得分:1)

而不是通过SetCurrentDirectory()更改目录,而是使用GetFiles()上的递归调用。这将要求调用者传入对数组(或std::vector<std::string>)的引用,以便存储要存储的文件列表,而不是使用本地数组s

答案 2 :(得分:1)

通过旧帖子进行一些搜索,我想我已经提到多次进行广度优先搜索,但从未真正发布过代码来展示如何进行搜索。我想我也可以这样做。

#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;
}

答案 3 :(得分:1)

为什么不使用提升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)
         );

答案 4 :(得分:0)

我要看一下boost的目录迭代器。

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

有一些例子涵盖了你想要做的事情,它几乎适用于你能想到的任何操作系统。

看看示例3.它显示了如何遍历目录的所有内容。如果你找到一个你以前没有见过的新目录,你就可以这样做了。有测试告诉你文件是否是常规的,目录等等,所以试一试。

相关问题