C++遍历文件夹方法
前言:C++17标准中增加了filesystem遍历文件夹方法,该方法与boost.filesystem中的相关方法基本相同。但某些原因导致,在项目中C++执行标准为14,测试了filesystem发现不能够顺利使用,便测试了一种适用于C++11标准的遍历文件夹方法便于自己使用,仅供参考。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <dirent.h>
#include <sys/stat.h>
void test_ItDir(const std::string& path)
{
DIR* dir = opendir(path.c_str());
if (dir == nullptr)
{
std::cerr << "Cannot open directory: " << path << std::endl;
return;
}
struct dirent* entry;
while ((entry = readdir(dir)) != nullptr)
{
std::string name = entry->d_name;
if (name == "." || name == "..")
{
continue;
}
std::string fullPath = path + "/" + name;
struct stat stat_buf;
if (stat(fullPath.c_str(), &stat_buf) != 0)
{
std::cerr << "Cannot stat file: " << fullPath << std::endl;
return;
}
// Determine whether it is a folder
if (S_ISDIR(stat_buf.st_mode))
{
std::cout << "Directory: " << fullPath << std::endl;
test_ItDir(fullPath);
}
else if (S_ISREG(stat_buf.st_mode))
{
std::cout << "File: " << fullPath << std::endl;
}
}
closedir(dir);
}
int main()
{
std::string path = "C:/Users/admin/Desktop/test";
test_ItDir(path);
return 1;
}
结果如图: