C++用FindFirstFile、FindNext递归遍历硬盘的文件

关于 WIN32_FIND_DATA 的数据结构

typedef struct _WIN32_FIND_DATA {
   DWORD dwFileAttributes; //文件属性

   FILETIME ftCreationTime; // 文件创建时间

   FILETIME ftLastAccessTime; // 文件最后一次访问时间

   FILETIME ftLastWriteTime; // 文件最后一次修改时间

   DWORD nFileSizeHigh; // 文件长度高32位

   DWORD nFileSizeLow; // 文件长度低32位

   DWORD dwReserved0; // 系统保留

   DWORD dwReserved1; // 系统保留

   TCHAR cFileName[ MAX_PATH ]; // 长文件名

   TCHAR cAlternateFileName[ 14 ]; // 8.3格式文件名

  } WIN32_FIND_DATA, *PWIN32_FIND_DATA;
#include <iostream>
#include <vector>
#include <windows.h>
using namespace std;


class SearchFile
{
private:
    vector<string>  result;
public:
    vector<string>  getResult()
    {
        auto   t = result;
        result.clear();
        return t;
    }
    bool  search(char *path="C:\\",char  *file="exe")
    {
        HANDLE hFile;
        char   buffer[MAX_PATH]={0,};
        WIN32_FIND_DATA pNextInfo;  //搜索得到的文件信息将储存在pNextInfo中;
        sprintf(buffer,"%s\\*.*",path);
        hFile = FindFirstFile(buffer,&pNextInfo);//请注意是 &pNextInfo , 不是 pNextInfo;
        if(!hFile){

            return false;
        }
        string  t;
        //cout << buffer << endl;
        while(FindNextFile(hFile,&pNextInfo))
        {

            if(pNextInfo.cFileName[0] == '.')//过滤.和..
                continue;
            //cout << pNextInfo.cFileName << endl;
            if(pNextInfo.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
            {
                ZeroMemory(buffer,MAX_PATH);
                sprintf(buffer,"%s\\%s",path,pNextInfo.cFileName);
                //cout << buffer << endl;
                search(buffer,file);
            }
            t.assign(path);
            t+='\\';
            t.append(pNextInfo.cFileName);
            int len = strlen(file);
            if(t.substr(t.size()-len)==file)
            {
                result.push_back(t);//对t对象进行深复制
            }

        }
        return true;
    }
};

int main() {

    SearchFile  s;
    //设计了一个SearchFile类来搜索文件,调用search成员函数后,再调用getResult()返回查到的结果,如果搜索失败,getResult()返回NULL
   s.search("C:\\Users\\lxw\\OneDrive\\python35","py");
    auto result = s.getResult();

    for(int i=0;i<result.size();i++)
    {
        cout << result[i] << endl;

    }
    return 0;
}

这里写图片描述
这里的IDE用的是CLion;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值