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;
}
希望能够对大家有所帮助~