c++ 递归搜索子文件

来源:互联网 发布:淘宝近千万卖家 编辑:程序博客网 时间:2024/06/06 01:39

很久之前用C++写了一个Windows下递归搜索所有子文件的函数,今天正好要用,就把它改了改,顺便分享一下^ ^


功能:

1. 递归查找某个路径下的所有子文件,文件名支持通配符(*或?)

2. 可以限制递归深度。

比如我知道我要找的文件肯定不会藏得太深,大概在1~2级子文件夹里吧,就可以限制最大搜索深度为2。这样就很节省时间。(强烈建议Windows自带的搜索能加上这个功能!)

3. 可以随时终止搜索。

只要有需要,随时可以停止搜索。比如我要找某个文档xxx.pdf,找到了就可以停了,不用继续把剩下的文件都遍历完,以免浪费资源。

4. 可以设置返回结果为子文件,还是子文件夹,还是子文件和子文件夹都返回。

5. 返回结果为路径、文件信息(文件名、属性、修改时间、访问时间等等),能够很方便地对结果进行处理。

6. 支持Unicode,同时尽可能减少了不必要的步骤,提升了处理速度。


使用方法:

比如搜索 C:\ 里面 *.exe ,最大深度为1。


#include <iostream>#include "enumsubfiles.h"#include <locale>int main(){//这台电脑上默认代码页是 936,std::wcout需要用到这个setlocale(CP_ACP, ".936");enumsubfiles(L"C:\\", L"*.exe", 1, ENUM_FILE, [](const std::wstring &dir, _wfinddata_t &attrib)->bool{//dir末尾有一个反斜杠'\\'std::wcout << dir << attrib.name << '\n';return true;          //return true继续搜索,return false停止搜索});return 0;}

输出的结果为:




代码:


enumsubfiles.h

#include <functional>#include <io.h>#include <string>enum enumflags {ENUM_FILE = 1,ENUM_DIR,ENUM_BOTH};//返回值://如果callback返回false终止了搜索,则enumsubfiles也返回false,//否则搜索完毕后返回truebool enumsubfiles(const std::wstring &dir_with_back_slant,  //根目录,比如: "L"C:\\", L"E:\\test\\"       const std::wstring &filename,             //比如: L"*", L"123.txt", L"*.exe", L"123.???"unsigned int maxdepth,                    //最大深度。0则不搜索子文件夹,-1则搜索所有子文件夹enumflags flags,                          //返回结果为文件,还是文件夹,还是都返回std::function<bool(const std::wstring &dir, _wfinddata_t &attrib)> callback);

enumsubfiles.cpp

#include "enumsubfiles.h"//返回值: //如果callback返回false终止了搜索,则enumsubfiles也返回false,//否则搜索完毕后返回truebool enumsubfiles(const std::wstring &dir_with_back_slant,  //根目录,比如: L"C:\\", L"E:\\test\\"        const std::wstring &filename,             //比如: L"*", L"123.txt", L"*.exe", L"123.???"unsigned int maxdepth,                    //最大深度。0则不搜索子文件夹,-1则搜索所有子文件夹enumflags flags,                          //返回结果为文件,还是文件夹,还是都返回std::function<bool(const std::wstring &dir, _wfinddata_t &attrib)> callback){_wfinddata_t dat;size_t hfile;std::wstring fullname = dir_with_back_slant + filename;std::wstring tmp;bool ret = true;hfile = _wfindfirst(fullname.c_str(), &dat);if (hfile == -1) goto a;do {if (!(wcscmp(L".", dat.name) && wcscmp(L"..", dat.name))) continue;if (((dat.attrib&_A_SUBDIR) && (!(flags&ENUM_DIR))) || ((!(dat.attrib&_A_SUBDIR)) && (!(flags&ENUM_FILE)))) continue;ret = callback(dir_with_back_slant, dat);if (!ret) {_findclose(hfile);return ret;}} while (_wfindnext(hfile, &dat) == 0);_findclose(hfile);a: if (!maxdepth) return ret;tmp = dir_with_back_slant + L"*";hfile = _wfindfirst(tmp.c_str(), &dat);if (hfile == -1) return ret;do {if (!(wcscmp(L".", dat.name) && wcscmp(L"..", dat.name))) continue;if (!(dat.attrib&_A_SUBDIR)) continue;tmp = dir_with_back_slant + dat.name + L"\\";ret = enumsubfiles(tmp, filename, maxdepth - 1, flags, callback);if (!ret) {_findclose(hfile);return ret;}} while (_wfindnext(hfile, &dat) == 0);_findclose(hfile);return ret;}


原创粉丝点击