c++接触不久老师给出了一个遍历文件夹的题目,一时没有做出来。
今天工作中需要用到这样的一个功能,于是又开始写了一个可以寻找某个后缀名称的路径集合的类CGetFilesPath。
主要的功能就是:指定一个目录和后缀名,类就可以返回这个后缀在该目录下的个数和每一个路径。
首先想到的是使用list,将遍历到的目录放入list,使用迭代指针记录Get的路径,以及下一个路径。
实现如下:
CGetFilesPath.h
// CGetFilesPath.h: interface for the COpenFiles class.
#if !defined(AFX_OPENFILES_H__12C595AF_2EBB_4426_A697_0F37B8A3B85A__INCLUDED_)
#define AFX_OPENFILES_H__12C595AF_2EBB_4426_A697_0F37B8A3B85A__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <list.h>
typedef list<CString> LIST_FILE;
class CGetFilesPath
{
public:
CGetFilesPath();
virtual ~CGetFilesPath();
//输入文件夹路径和后缀,获得所有文件,返回成功、失败
bool SetsearchPath(const CString filepath, const CString fileSuffix);
//获取文件的个数
int GetFileNum();
//获取第一个文件路径
CString GetFirstFile();
//获取下一个文件路径
CString GetNextFile();
//清空
void DeleteFilePath();
protected:
private:
LIST_FILE listfile;
LIST_FILE::iterator it_list;
};
#endif // !defined(AFX_OPENFILES_H__12C595AF_2EBB_4426_A697_0F37B8A3B85A__INCLUDED_)
OpenFiles.cpp
// OpenFiles.cpp: implementation of the COpenFiles class.
#include "stdafx.h"
#include "CGetFilesPath.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//
// Construction/Destruction
//
CGetFilesPath::CGetFilesPath()
{
it_list = listfile.begin();
}
CGetFilesPath::~CGetFilesPath()
{
listfile.clear();
}
bool CGetFilesPath::SetsearchPath(const CString filepath, const CString fileSuffix)
{
if ("" == filepath || "" == fileSuffix)
{
return false;
}
CString strFolderName = filepath;
CString strExt = fileSuffix;
int i = 0;
CFileFind fFinder;
BOOL bIsFind;
CString strFindComment;
CString strSearchComment;
if (0 == strFolderName.GetLength())
strSearchComment = "*.*";
else if (0 != strFolderName.Right(1).CompareNoCase("\\"))
strSearchComment = "\\*.*";
else if (0 == strFolderName.Right(1).CompareNoCase("\\"))
strSearchComment = "*.*";
bIsFind = fFinder.FindFile( strFolderName + strSearchComment );
while( bIsFind )
{
bIsFind = fFinder.FindNextFile();
strFindComment = fFinder.GetFilePath();
if ( fFinder.IsDirectory() && !fFinder.IsDots() )
{
SetsearchPath( strFindComment,strExt);
}
else if ( !fFinder.IsDirectory() && !fFinder.IsDots() )
{
if (0 == strFindComment.Right(strExt.GetLength()).CompareNoCase( strExt ))
{
listfile.push_back(strFindComment);
i++;
}
}
}
return true;
}
int CGetFilesPath::GetFileNum()
{
int i = listfile.size();
return i;
}
CString CGetFilesPath::GetFirstFile()
{
if (0 == listfile.size())// 错误处理
{
return "";
}
CString tempstr;
it_list = listfile.begin();
tempstr = *it_list;
it_list++;
return tempstr;
}
CString CGetFilesPath::GetNextFile()
{
CString tempstr;
if (listfile.end() != it_list)
{
tempstr = *it_list;
it_list++;
return tempstr;
}
else
{
return "";
}
}
void CGetFilesPath::DeleteFilePath()
{
listfile.clear();
it_list = listfile.begin();
}