標籤:closed inf read 遞迴 info 賦值 get sign dir
windows版本
#include <iostream>#include <io.h>#include <fstream>#include <string>#include <sstream>using namespace std;void getAllFiles(string path, vector<string>& files){ //檔案控制代碼 long hFile = 0; //檔案資訊 struct _finddata_t fileinfo; //很少用的檔案資訊讀取結構 string p; //string類很有意思的一個賦值函數:assign(),有很多重載版本 if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1) { do { if ((fileinfo.attrib & _A_SUBDIR)) //比較檔案類型是否是檔案夾 { if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0) { files.push_back(p.assign(path).append("/").append(fileinfo.name)); getAllFiles(p.assign(path).append("/").append(fileinfo.name), files); } } else { files.push_back(p.assign(path).append("/").append(fileinfo.name)); } } while (_findnext(hFile, &fileinfo) == 0); //尋找下一個,成功返回0,否則-1 _findclose(hFile); }}int main(){ char * inPath = "./srcImg"; vector<string> files; //測試 char * distAll = "AllFiles.txt"; getAllFiles(inPath, files); ofstream ofn(distAll); int size = files.size(); ofn << size << endl; for (int i = 0; i<size; i++) { ofn << files[i] << endl; } ofn.close(); return 0;}
linux版本
#include <iostream>#include <string>#include <iostream>#include <string>#include <vector>#include <fstream>extern "C"{ #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <errno.h> #include <dirent.h> #include <stdio.h> #include <stdlib.h> #include <string.h>}using namespace std;void getAllFiles(string path, vector<string>& files){ DIR *dir; struct dirent *ptr; if((dir=opendir(path.c_str()))==NULL){ perror("Open dri error..."); exit(1); } while((ptr=readdir(dir))!=NULL){ if(strcmp(ptr->d_name,".")==0||strcmp(ptr->d_name,"..")==0) continue; else if(ptr->d_type==8)//file files.push_back(path+"/"+ptr->d_name); else if(ptr->d_type==10)//link file continue; else if(ptr->d_type==4){ //files.push_back(ptr->d_name);//dir getAllFiles(path+"/"+ptr->d_name,files); } } closedir(dir);}int main(int argc,char **argv){ if(argc<2){ cout<<"USAGE:./a.out path"<<endl; exit(-1); } char * filePath = argv[1]; vector<string> files; char * distAll = "allFiles.txt"; getAllFiles(filePath, files); ofstream ofn(distAll); int size = files.size(); //ofn << size << endl; for (int i = 0; i<size; i++) { ofn << files[i] << endl; } ofn.close(); return 0;}
C++ 遞迴讀取目錄下所有檔案