//C++ 按关键字搜索文件夹中的文件 #include<iostream> #include<string> #include<io.h> using namespace std; void filesearch(string path,string mode) { struct _finddata_t filefind; if(path[path.size()-1]=='\\') path.resize(path.size()-1); string curr=path+"\\*.*"; int done=0,handle; if((handle=_findfirst(curr.c_str(),&filefind))==-1) return; while(!(done=_findnext(handle,&filefind))) { if(!strcmp(filefind.name,"..")) continue; curr=path+"\\"+filefind.name; if(strstr(filefind.name,mode.c_str())) cout<<curr<<endl; if (_A_SUBDIR==filefind.attrib) filesearch(curr,mode); } _findclose(handle); } void main() { string path,mode; cout<<"请输入要搜的目录"<<endl; cin>>path; cout<<"请输出包含字符"<<endl; cin>>mode; filesearch(path,mode); } /*--- 请输入要搜的目录 d:\ 请输出包含字符 qq d:\song_tool\VC界面类编程实例与源码\用c++做的qq界面 d:\song_tool\other\user.qzone.qq.com865421364.html d:\song_tool\播放器\VC界面大全\用c++做的qq界面 d:\NEO_V2[1][1].1.90\NEO_V2.1.90\tools\图标文件\qq.ico Press any key to continue ----*/ ★参考资料★ http://www.ok2002.com/cc/html/0vde94fj-lxk7_c2jfd3c3mxyobbt5n1u0azpl4rnwymui781eogz.q.vak6-gt2.html ======================================================================================#include<stdio.h> #include<windows.h>
void FindFile(char* ,char* ); int count=0;//统计文件数 char fname[32]; #define BUFSIZE 256 int main(int argc,char* argv[]) { char szLogicalDriveStrings[BUFSIZE]; DWORD iLength; int iSub; printf("请输入要搜索的文件名:"); scanf("%s",fname); ZeroMemory(szLogicalDriveStrings, BUFSIZE); iLength = GetLogicalDriveStringsA(BUFSIZE-1, szLogicalDriveStrings); for(iSub=0; iSub<iLength; iSub+=4) { //如果不是固定磁盘驱动器:本地硬盘或移动硬盘,忽略 if(GetDriveType(szLogicalDriveStrings+iSub)!=3) continue; FindFile(szLogicalDriveStrings+iSub,"*.*"); } printf("一共发现%d个文件...\n",count); scanf("%*d"); return 0; }
void FindFile(char* pfilename,char* pfilter) { WIN32_FIND_DATA findfiledate; HANDLE hfind; char filename[512]; char lpFileName[512]; char _lpFileName[512]; int i; int result; for(i=0;*(pfilename+i)!='\0';i++) filename[i]=*(pfilename+i); filename[i]='\0'; //如果最后一个字符不是'\' if(filename[strlen(filename)-1]!='\\') strcat(filename,"\\"); //添加'\' strcpy(lpFileName,filename); strcat(lpFileName,pfilter); hfind=FindFirstFile(lpFileName,&findfiledate); if(hfind==INVALID_HANDLE_VALUE) return; do { //如果不是目录 if(!(findfiledate.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)) { //如果找到指定文件 if(0==strcmp(fname,findfiledate.cFileName)) { printf("%s%s\n",filename,findfiledate.cFileName); count++; } } //如果是目录 else { //.和..不输出 if(findfiledate.cFileName[0]!='.') { strcpy(_lpFileName,filename); strcat(_lpFileName,findfiledate.cFileName); FindFile(_lpFileName,pfilter); //递归 } } }while(FindNextFile(hfind,&findfiledate));//FindNextFile返回为真,继续搜索 FindClose(hfind); return; }
C++ 按关键字搜索文件夹中的文件 & 全盘符搜索文件
最新推荐文章于 2023-09-28 23:47:40 发布