在做一个东西时需要扫描目录下所有图片,于是就产生了如下的东西
给定速要扫描的路径,则以其为根目录扫描其下所有目录和文件,并且还可以设定扫描的深度
P.S.:
1. 扫描是递归实现的,所以缺点很明显。
2. 在扫描过程中会用到用户指定的回调函数,并且会将文件类型和名字一并传入,以便用户自行决定是否需要将其添加到tree控件中。
头文件
#include <functional>
class CFolderScanner
{
private:
CTreeCtrl *pTreeCtrl;
CList<HTREEITEM , HTREEITEM> FolderRootStack;
public:
CFolderScanner(void);
~CFolderScanner(void);
void SetTree(CTreeCtrl *pTree);
CTreeCtrl* GetTreeCtrl();
// 在指定的根目录下扫描文件和文件夹,并将扫描到的名字和类型传入回调函数中.同时第二个参数指定扫描文件夹的深度.
// 回调函数返回值:
// 0 : 添加当前项,如果是文件夹则不继续深入扫描
// 1 : 添加当前项,如果是文件夹则继续深入扫描
// -1 : 不要当前项,如果是文件夹则自然不会深入
void ScanFolder(LPCTSTR RootFolder , int Level , std::tr1::function<int (bool , CString& , int)> CallBack_);
void GetFileList(LPCTSTR FolderPath , CArray<CString , CString&> FileArray);
CString GetPath(HTREEITEM hItem , LPCTSTR separator = NULL);
};
实现
#include "StdAfx.h"
#include "FolderScanner.h"
CFolderScanner::CFolderScanner(void)
{
pTreeCtrl = NULL;
}
CFolderScanner::~CFolderScanner(void)
{
}
void CFolderScanner::SetTree( CTreeCtrl *pTree )
{
pTreeCtrl = pTree;
}
CTreeCtrl* CFolderScanner::GetTreeCtrl()
{
return pTreeCtrl;
}
void CFolderScanner::ScanFolder( LPCTSTR RootFolder , int Level , std::tr1::function<int (bool , CString& , int)> CallBack_ )
{
ASSERT(pTreeCtrl);
CFileFind file;
CString FolderPath(RootFolder);
int i = file.FindFile(FolderPath+_T("\\*.*"));
if(FolderPath.Right(1) != _T("\\"))
FolderPath += L"\\";
bool isFolder = false;
CString Name;
bool isLastOne = false;
HTREEITEM Root_tmp;
while (1)
{
if (!file.FindNextFile())
isLastOne = true;
if (file.IsDots())
{
if (isLastOne)
break;
else
continue;
}
if (file.IsDirectory())
{
isFolder = true;
Name = file.GetFileName();
}
else
{
isFolder = false;
Name = file.GetFileName();
}
int ReVal = CallBack_(isFolder , Name , Level);
if (-1 != ReVal)
{
if (!FolderRootStack.GetCount())
Root_tmp = NULL;
else
Root_tmp = FolderRootStack.GetHead();
Root_tmp = pTreeCtrl->InsertItem(Name , 0 , 0 , Root_tmp);
if (1 == ReVal && (1 < Level || -1 == Level))
{
FolderRootStack.AddHead(Root_tmp);
ScanFolder(FolderPath + Name ,(-1 == Level)? -1 : Level - 1 , CallBack_); // 深入遍历子目录
}
}
if (isLastOne)
break;
}
if (FolderRootStack.GetCount())
FolderRootStack.RemoveHead();
}
void CFolderScanner::GetFileList( LPCTSTR FolderPath , CArray<CString , CString&> FileArray )
{
CFileFind fileFind;
CString Path(FolderPath);
bool OK = fileFind.FindFile(Path+_T("\\*.*"));
while (OK)
{
if (!fileFind.FindNextFile())
OK = false;
if (!fileFind.IsDots() && !fileFind.IsDirectory())
{
FileArray.Add(fileFind.GetFilePath());
}
}
}
CString CFolderScanner::GetPath( HTREEITEM hItem , LPCTSTR separator /**//*= NULL*/ )
{
CString ReturnVal = pTreeCtrl->GetItemText(hItem);
while(hItem = pTreeCtrl->GetParentItem(hItem))
{
ReturnVal = pTreeCtrl->GetItemText(hItem) + (separator ? separator : _T("\\")) + ReturnVal;
}
return ReturnVal;
}
posted on 2011-01-09 20:44
zhaoyg 阅读(793)
评论(0) 编辑 收藏 引用 所属分类:
MFC学习笔记