1. 程式人生 > >C++ 按關鍵字搜尋資料夾中的檔案 & 全碟符搜尋檔案

C++ 按關鍵字搜尋資料夾中的檔案 & 全碟符搜尋檔案

//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; }