windows:
使用標頭檔:<io.h>、<direct.h>
關鍵函數:_findfirst、_findnext
關鍵結構體:_finddata_t
_finddata_tfileinfo;intptr_t hFile;string root;root.assign(Path);//檔案夾絕對路徑int len = root.length();if ( !IsEndObliqueLine(Path) )//路徑的結尾不是‘\’{root.append("\\");}root.append("*");//路徑下的所有檔案hFile = _findfirst(root.c_str(), &fileinfo);if ( -1 == hFile){assert(false);return;}strcpy(m_CurrentPath, Path);//儲存到m_CurrentPath//清空之前Path的資訊FilesPathVector.clear();//自訂的儲存資訊的容器do //儲存資訊{LISTCMD_INFO TmpDirInfo = {0};TransFileInfo(fileinfo, TmpDirInfo);FilesPathVector.push_back(TmpDirInfo);}while(_findnext(hFile, &fileinfo) == 0);
linux:
使用標頭檔: <dirent.h>、 <sys/types.h>、<sys/stat.h>
關鍵函數:readdir、lstat
關鍵結構體:dirent
DIR *dir;if ( !(dir = opendir(Path)) ){assert(false);return;} strcpy(m_CurrentPath, Path);//儲存到m_CurrentPathstruct dirent *d_ent;char fullpath[128];FilesPathVector.clear();while ( (d_ent = readdir(dir)) != NULL ){struct stat file_stat;//if ( strncmp(d_ent->d_name, ".", 1) == 0 )//{//continue;// 忽略"."目錄//}memset(fullpath, '\0', sizeof(fullpath));strcpy( fullpath, Path);if ( !strcmp(fullpath, "/") ){fullpath[0] = '\0';}strcat(fullpath, "/");strcat(fullpath, d_ent->d_name);if ( lstat(fullpath, &file_stat) < 0 ){assert(false);return;}//儲存資訊到自己的資料結構,在函數外面儲存檔案名稱LISTCMD_INFO TmpDirInfo = {0};strcpy(TmpDirInfo.cFileName, d_ent->d_name);TransFileInfo(&file_stat, TmpDirInfo);FilesPathVector.push_back(TmpDirInfo);}closedir(dir);
值得注意的是,此種方法windows的路徑分隔是用'\',而linux用'/',使用時多少有點不便。
如果有其他更好得方法,歡迎交流!