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

时间:2022-06-18 21:35:56

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);
}


测试通过!


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