遍历文件夹及其子文件夹下所有文件
来源:互联网 发布:java多线程并发控制 编辑:程序博客网 时间:2024/05/16 19:32
void dfsFolder(string folderPath, ofstream &fout){ _finddata_t FileInfo; string strfind = folderPath + "\\*"; long Handle = _findfirst(strfind.c_str(), &FileInfo); if (Handle == -1L) { cerr << "can not match the folder path" << endl; exit(-1); } do{ //判断是否有子目录 if (FileInfo.attrib & _A_SUBDIR) { //这个语句很重要 if( (strcmp(FileInfo.name,".") != 0 ) &&(strcmp(FileInfo.name,"..") != 0)) { string newPath = folderPath + "\\" + FileInfo.name; dfsFolder(newPath, fout); } } else { fout << folderPath << "\\" << FileInfo.name << " "; } }while (_findnext(Handle, &FileInfo) == 0); _findclose(Handle); fout.close();}
void FindFile(wchar_t *pFilePath) { WIN32_FIND_DATA FindFileData; HANDLE hFind = INVALID_HANDLE_VALUE; wchar_t DirSpec[MAX_PATH + 1];// 指定路径 DWORD dwError; wcsncpy (DirSpec, pFilePath, wcslen(pFilePath) + 1); wcsncat (DirSpec, L"\\\*", 3); hFind=FindFirstFile(DirSpec,&FindFileData); if (hFind == INVALID_HANDLE_VALUE) { wprintf(L"Invalid file handle. Error is %u ", GetLastError()); return ; } bool bFinish=false; while(!bFinish) { if (FindFileData.dwFileAttributes != FILE_ATTRIBUTE_DIRECTORY ) { wchar_t temp[3000]; memset(temp,0,3000*sizeof(wchar_t)); //wprintf_s(temp,L"%S\\%S\n",pFilePath,FindFileData.cFileName); wcscpy(temp,pFilePath); wcscat(temp,L"\\"); wcscat(temp,FindFileData.cFileName); string rawtext=""; string line; ifstream infile; infile.open(temp); if(infile) { while(getline(infile,line)) { rawtext+=line; } } infile.clear(); infile.close(); InsertArticlesToDataBase(rawtext); } bFinish = (FindNextFile(hFind, &FindFileData) == false); } }