使用C++查找某个文件夹下的所有的文件和文件夹

string 中find();查找函数有一个唯一的返回类型,就是size_type:一个无符号的整数,查找成功:返回按查找规则找到第一个字符或者子串的位置,查找失败,则返回npos.

void GetChildFilesWithExt(const std::string basePath, std::vector<std::string> &files, bool searchSubDir, std::string ext)

{
std::vector<std::string> all_files;  //声明一个vector用来存储所有的文件和文件夹
GetChildFiles(basePath, all_files, searchSubDir);
for (std::string & file_path : all_files) {   //遍历
int rfind_ext = file_path.rfind(ext);  //从后边向前找,是否有某个字符串
if (rfind_ext == file_path.length() - ext.length()) { 
files.push_back(file_path);
}
}

}

//这个函数包括在windows中查找文件夹和文件名字,其中使用递归的方式查找其中基路径后的所有的文件夹和循环查找其中的文件。

void GetChildFiles(const std::string basePath, std::vector<std::string> &files,bool searchSubDir)
{
//验证basePath路径
#ifdef _WIN32
long   hFile = 0;//文件句柄
struct _finddata_t fileinfo;//文件信息
if ((hFile = _findfirst((basePath + "/*").c_str(), &fileinfo)) == -1)
return;
#else
DIR *dir;
struct dirent *ptr;
if ((dir = opendir(basePath.c_str())) == NULL)
return;
#endif
//获取文件列表
#ifdef _WIN32
do {
if (strcmp(fileinfo.name, ".") == 0 || strcmp(fileinfo.name, "..") == 0)
continue;
#else
while ((ptr = readdir(dir))) {
if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0)
continue;
#endif
//当前路径
std::string curFilePath;
//如果当前子路径是目录,并且需要递归
#ifdef _WIN32
//curFilePath =   fileinfo.name;
curFilePath = basePath + "/" + fileinfo.name;
if ((fileinfo.attrib &  _A_SUBDIR) && searchSubDir)
#else
//curFilePath =   ptr->d_name;
curFilePath = basePath + "/" + fileinfo.name;
if (ptr->d_type == 4 && searchSubDir)
#endif
GetChildFiles(curFilePath, files, searchSubDir);//则递归获取子文件夹
   //当前路径加入列表
files.push_back(curFilePath);
//关闭文件
#ifdef _WIN32
}while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
#else
}
closedir(dir);
#endif
}

猜你喜欢

转载自blog.csdn.net/u010565765/article/details/79168898