1. 程式人生 > >【C++】讀取路徑目錄下指定型別檔案列表

【C++】讀取路徑目錄下指定型別檔案列表

Overview

所編寫getAllFiles函式:

int getAllFiles(const string path, vector<string> &files, const string fileType, bool recurseSubdir, bool verbose);

從路徑目錄中讀取指定型別檔案列表,成功返回1,失敗返回0

  • 輸入path:形式為string的路徑目錄

  • 輸出files:形式為vector<string>的檔案列表

  • 引數fileType:檔案拓展名 “.abc” 形式

  • 可選引數recurseSubdir:是否遞迴子資料夾

  • 可選引數verbose:是否輸出檔案資訊

  • 檔案分隔符:根據不同系統由巨集定義

Code

#include <io.h>
#include <string>
#include <vector>
#include <iostream>

using namespace std;

#if defined(_WIN32) || defined(_WIN64)
#define FILEseparator "\\"
#else
#define FILEseparator "/"
#endif

// Get all files list under certain path,specific file type,recursive,success return 1,failure return 0
int getAllFiles(const string path, vector<string> &files, const string fileType = ".jpg", bool recurseSubdir = true, bool verbose = true) { // File handle long hFile = 0; // File data structure struct _finddata_t fileInfo; string p; // string.assign():Assignment function,clear origin string,then replace with new string,several overloads
if ((hFile = _findfirst(p.assign(path).append(FILEseparator).append("*").c_str(), &fileInfo)) != -1) { do { // Current filename p.assign(path).append(FILEseparator).append(fileInfo.name); // Recurse if subdirectory if(fileInfo.attrib & _A_SUBDIR) { if (recurseSubdir && strcmp(fileInfo.name, ".") != 0 && strcmp(fileInfo.name, "..") != 0) { if (verbose) { cout << "SubDir:" << p << endl; } // Recurse current subdirectory getAllFiles(p, files, fileType, recurseSubdir); } } // Enroll if not subdirectory else { // Judge file extension name if (strcmp((p.substr(p.size() - fileType.size())).c_str(), fileType.c_str()) == 0) { if (verbose) { cout << "File:" << p << endl; } // Save to vector files.push_back(p); } } } // Find the next one,success return 0,else -1 while (_findnext(hFile, &fileInfo) == 0); // close handle _findclose(hFile); return 1; } else return 0; }

希望能夠對大家有所幫助~