C++ 遍历文件夹以及子文件夹下所有文件

本文介绍了一种改进的文件及子文件夹遍历方法,解决了CFileFind在特定情况下无法遍历含有单一中文名文件夹的问题。使用_finddata_t结构和_findfirst/_findnext函数实现了稳定可靠的遍历逻辑。

CFileFind 所提供的方法进行文件夹以及子文件夹遍历时,经过测试会出现如果当前遍历的路径为盘符,且盘符中仅包含一个中文文件夹(文件夹名以汉字开头),此时遍历不到该文件夹。


所以采用以下方法(需要添加头#include "io.h" )

void GetAllFileFromPath(CString folderPath)
{
	if (folderPath == _T(""))
	{
		return;
	}

	_finddata_t FileInfo;
	CString strfind = folderPath + "\\*";
	long Handle = _findfirst(strfind, &FileInfo);

	if (Handle == -1L)
	{
		_findclose(Handle);
		return;
	}
	do{
		if (FileInfo.attrib & _A_SUBDIR)
		{
			if ((strcmp(FileInfo.name, ".") != 0) && (strcmp(FileInfo.name, "..") != 0))
			{
				CString newPath = folderPath + "\\" + FileInfo.name;
				GetAllFileFromPath(newPath);
			}
		}
		else
		{
			CString strFindName = TMGetFileExt(FileInfo.name);
			{
				//此处记录文件 strFindName 
			}
		}
	} while (_findnext(Handle, &FileInfo) == 0);

	_findclose(Handle);
}


测试通过!


仅做笔记记录,请网友指正!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值