C++ 遍历文件夹(含详细代码)

遍历当前目录

/****************************************
*   遍历当前目录下的文件夹和文件,默认是按字母顺序遍历
****************************************/
#include<io.h>
#include<iostream>
using namespace std;
bool FindAllFilesOnCurFolder(string path, int &file_num)
{
	_finddata_t file_info;
	//可以定义后面的后缀为*.exe,*.txt等来查找特定后缀的文件,*.*是通配符,匹配所有类型,路径连接符最好是左斜杠/,可跨平台
	string current_path = path + "/*.*";   
	int handle = _findfirst(current_path.c_str(), &file_info);
	//返回值为-1则查找失败  
	if (-1 == handle)
		return false;
	do
	{
		string attribute;
		if (file_info.attrib == _A_SUBDIR) //是目录  
			attribute = "dir";
		else
			attribute = "file";
		
		//获得的最后修改时间是time_t格式的长整型
		cout << file_info.name << ' ' << file_info.time_write << ' ' << file_info.size << ' ' << attribute << endl;  
		file_num++;

	} while (!_findnext(handle, &file_info));
	
	//关闭文件句柄  
	_findclose(handle);
	return true;
}

遍历当前目录及所有子目录

/*
*深度优先递归遍历当前目录下的文件夹、文件及子文件夹和文件
*/
#include<io.h>
#include<iostream>
using namespace std;
void DfsListFolderFiles(string path)
{
	_finddata_t file_info;
	string current_path = path + "/*.*"; 
	int handle = _findfirst(current_path.c_str(), &file_info);
	//返回值为-1则查找失败  
	if (-1 == handle)
	{
		cout << "cannot match the path" << endl;
		return;
	}

	do
	{
		//目录  
		if (file_info.attrib == _A_SUBDIR)
		{
			cout << file_info.name << endl;
			//.是当前目录,..是上层目录,须排除掉这两种情况
			if (strcmp(file_info.name, "..") != 0 && strcmp(file_info.name, ".") != 0)   
				DfsListFolderFiles(path);   
		}
		else
		{
			cout << file_info.name << endl;
		}
	} while (!_findnext(handle, &file_info)); 
   //关闭文件句柄  
	_findclose(handle);
}

重要说明

欢迎大家关注我的个人微信公众号,一起探讨和学习C++语言、各种计算机知识、交流职场心得,以及您想了解的各种程序员相关的知识与心得!

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/siyacaodeai/article/details/112732678