写了一个小函数,贴出来给参考参考。输入是,你要搜索的顶层目录,第二个参数是你需要存放结果的列表,第三个参数,为你写的正则表达式。十分简单。效率很高。
#include <list>
#include <string.h>
#include <string>
using namespace std ;
void RegexMatchAndSave(const char *FileName,char *path,list<string> *filelist,string regexexpression)
{
regex Hrdacexp(regexexpression);
cmatch what; string in=FileName ;
if(regex_match(in.c_str(),what,Hrdacexp))
{
char buf[500];memset(buf,0,500);
strcat(buf,path); strcat(buf,what[0].str().c_str());
filelist->push_back(buf);
}
else
{
cout<<"File type Error Match"<<endl;
}
}
void SearchFilesOnPath(char *path,list<string> *filelist,string regexexpression)
{
DIR *dirptr = NULL;
struct dirent *entry;
if(path==NULL)
{
printf("please input dir you want to read\n");
Fprint_String("PATH NULL ERROR","StdDataServerError","a+");
exit(-1);
}
if((dirptr = opendir(path)) == NULL)
{
printf("open dir %s !\n",path);
}
else
{
do
{
entry = readdir(dirptr) ;
if(entry!=NULL)
{
if(entry->d_type == 0x04 && (strcmp((const char*)entry->d_name,"..")!=0) && (strcmp((const char*)entry->d_name,".")!=0))
{
printf("###%s is dir and isn't \" ..\" nor \".\"\n", entry->d_name);
char buf[500];memset(buf,0,500);
strcat(buf,path); strcat(buf,entry->d_name);strcat(buf,"/");
SearchFilesOnPath(buf,filelist,regexexpression);
}
else if (entry->d_type == 0x08)
{
printf("%s is file ,match now \n", entry->d_name);
RegexMatchAndSave(entry->d_name,path,filelist,regexexpression);
}
else{
printf("What type is it ??\n");
}
}
}while (entry);
closedir(dirptr);
printf("File Search over now to Show consequence\n\n");
list<string>::iterator iter;
for(iter=filelist->begin();iter!=filelist->end();iter++)
{
printf("%s\n",(*iter).c_str());
}
}
}