您的位置:首页 > 其它

MFC递归遍历目录下所有子目录和文件

2011-04-29 15:56 597 查看
在MFC下要实现文件夹的递归遍历,可用CFileFind类,依次读取文件夹下的子文件夹和文件,并判断通过判断是文件夹还是文件来决定递归遍历(事实上,CFileFind本身还可以判断文件具体属于哪种类型,例如压缩文件、系统文件等)。另外要注意,遍历过程中会读到"."文件和".."文件,可通过fileFinder.IsDots()函数识别。

相关代码:

//Bayes测试函数(递归)
void CTestPage::BayesCategoryTest(BayesTest* bt, CString tp)
{
CFileFind fileFinder;
CString filePath = tp + _T("//*.*");

BOOL bFinished = fileFinder.FindFile(filePath);
while(bFinished) //每次循环对应一个类别目录
{
bFinished = fileFinder.FindNextFile();
if(fileFinder.IsDirectory() && !fileFinder.IsDots()) //若是目录则递归调用此方法
{
BayesCategoryTest(bt, fileFinder.GetFilePath());
}
else //再判断是否为txt文件
{
//获取文件类型
CString fileName = fileFinder.GetFileName();
int dotPos=fileName.ReverseFind('.');
CString fileExt=fileName.Right(fileName.GetLength()-dotPos);
if(fileExt == _T(".txt")) //若是txt文件则开始分类测试
{
CString category = fileName.Left(fileName.GetLength()-8); //应属类
CString result = bt->StartTest(fileFinder.GetFilePath()); //所分类

int n = m_ListCtrl.GetItemCount();
m_ListCtrl.InsertItem(n, fileName,0);// 插入为第n行第一列的内容:文件名
m_ListCtrl.SetItemText( n,1, category) ; // 设置第n行第列的内容:应属类
m_ListCtrl.SetItemText(n,2, result) ; // 设置第n行第列的内容:所分类
if(category == result)
m_ListCtrl.SetItemText(n,3, _T("Correct!")) ; //判断正确
else
m_ListCtrl.SetItemText(n,3, _T("Wrong!")) ; //判断错误

}
}
}

fileFinder.Close();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: