windows和linux擷取檔案夾內容的一種方法

來源:互聯網
上載者:User

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用'/',使用時多少有點不便。

如果有其他更好得方法,歡迎交流!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.