当前位置:   article > 正文

C++11标准中遍历文件夹方法_c++11 遍历文件夹

c++11 遍历文件夹

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53

结果如图:
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/281804
推荐阅读
相关标签
  

闽ICP备14008679号