在c ++中查找所有目录中的所有文件 [英] Find all files in all directories in c++

查看:368
本文介绍了在c ++中查找所有目录中的所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到所有目录中的所有文件,但我不知道如何处理子目录。在这段代码中,代码看起来遍历所有的子代,但是我不知道如何跳回去。有没有人知道如何做到这一点?
$ b $ pre $ __ 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 ++; (FindNextFile(hFind,& ffd)> = 0);
}
}
。 //如果返回0,则需要跳回

FindClose(hFind);





编辑:函数具有相同的名称,而不是通过 SetCurrentDirectory()更改目录,而是使用递归调用的GetFiles()。这将要求调用者传递对数组(或 std :: vector > )的引用来存储文件列表,而不是使用本地数组 s


I am trying to find all files in all directories, but I don't know how to handle subdirectories. In this code, the code looks trough all subdirs, but I don't know how to jump back. Does anyone know how to do this?

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

EDIT: functions had the same name which confused the compiler

解决方案

Instead of changing directory via SetCurrentDirectory() use a recursive call on GetFiles(). This would require that the caller pass in a reference to an array (or std::vector<std::string>) for the list of files to be stored in instead of using the local array s.

这篇关于在c ++中查找所有目录中的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆