#include <string>
#include <iostream>
#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);
}
c++ 11遍历文件夹的文件
C++遍历目录及其内容
最新推荐文章于 2025-08-13 10:07:56 发布
该代码段展示了一个用C++编写的函数,用于打开并遍历指定路径下的目录。它使用dirent.h和sys/stat.h库,检查每个条目是文件还是子目录,并打印相关信息。对于子目录,函数会递归进行相同的操作。
475

被折叠的 条评论
为什么被折叠?



