本篇文章為大家展示了如何在C++中獲取指定目錄中的所有文件,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
目前成都創(chuàng)新互聯(lián)已為上千余家的企業(yè)提供了網(wǎng)站建設(shè)、域名、雅安服務(wù)器托管、綿陽服務(wù)器托管、企業(yè)網(wǎng)站設(shè)計、景谷網(wǎng)站維護等服務(wù),公司將堅持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長,共同發(fā)展。
1.獲得指定目錄下的所有文件(不搜索子文件夾)
需要包含的頭文件
#include <io.h> #include <string> #include <vector> #include <fstream>
函數(shù)實現(xiàn)
void getAllFiles(string path, vector<string>& files) { // 文件句柄 long hFile = 0; // 文件信息 struct _finddata_t fileinfo; string p; if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1) { do { // 保存文件的全路徑 files.push_back(p.assign(path).append("\\").append(fileinfo.name)); } while (_findnext(hFile, &fileinfo) == 0); //尋找下一個,成功返回0,否則-1 _findclose(hFile); } }
2.獲取指定目錄下的所有文件(搜索子文件夾)
void getAllFiles(string path, vector<string>& files) { //文件句柄 long hFile = 0; //文件信息 struct _finddata_t fileinfo; string p; 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); } }
3.獲取指定格式的文件(不搜索子文件夾)
/* path: 指定目錄 files: 保存結(jié)果 fileType: 指定的文件格式,如 .jpg */ void getAllFiles(string path, vector<string>& files,string fileType) { // 文件句柄 long hFile = 0; // 文件信息 struct _finddata_t fileinfo; string p; if ((hFile = _findfirst(p.assign(path).append("\\*" + fileType).c_str(), &fileinfo)) != -1) { do { // 保存文件的全路徑 files.push_back(p.assign(path).append("\\").append(fileinfo.name)); } while (_findnext(hFile, &fileinfo) == 0); //尋找下一個,成功返回0,否則-1 _findclose(hFile); } }
4.測試
int main(int argc, char** argv) { vector<string> temp; getAllFiles("J:\\faces\\test", temp,".jpg"); for (int i = 0; i < temp.size();++i ) { cout << temp[i] << endl; } return 0; }
上述內(nèi)容就是如何在C++中獲取指定目錄中的所有文件,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
本文標(biāo)題:如何在C++中獲取指定目錄中的所有文件
網(wǎng)頁網(wǎng)址:http://chinadenli.net/article6/jsidog.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供域名注冊、云服務(wù)器、網(wǎng)站策劃、虛擬主機、自適應(yīng)網(wǎng)站、外貿(mào)網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)