c++ 實現跨平臺的目錄遍歷
#ifdef _WIN32 #include <io.h> #else #include <unistd.h> #include <stdio.h> #include <dirent.h> #include <sys/stat.h>
#endif
win32平臺引用io.h裡面的資訊。
主要定義了一個void dfsFolder(string folderPath, int depth = 0);方法對其進行遞迴遍歷。
具體的實現為
void dfsFolder( string folderPath, int depth) { #ifdef WIN32 _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); } } else { string filename = (folderPath + "\\" + FileInfo.name); 28 cout << folderPath << "\\" << FileInfo.name << " " << endl; } }while (_findnext(Handle, &FileInfo) == 0); _findclose(Handle); #else DIR *dp; struct dirent *entry; struct stat statbuf; if((dp = opendir(folderPath.c_str())) == NULL) { fprintf(stderr,"cannot open directory: %s\n", folderPath.c_str()); return; } chdir(folderPath.c_str()); while((entry = readdir(dp)) != NULL) { lstat(entry->d_name,&statbuf); if(S_ISDIR(statbuf.st_mode)) { if(strcmp(".",entry->d_name) == 0 || strcmp("..",entry->d_name) == 0) continue; printf("%*s%s/\n",depth,"",entry->d_name); dfsFolder(entry->d_name,depth+4); } else { string filename = entry->d_name; 54 printf("%*s%s\n",depth,"",entry->d_name); } } chdir(".."); closedir(dp); #endif }
chdir 是C語言中的一個系統呼叫函式(同cd),其中對目錄"."及".."進行特殊的判斷,因為"."是表示當前目錄,".."表示父目錄。
如果不進行特殊判定的話則進入死迴圈。
一個很簡單的功能,希望可以幫助得到需要的同學們~