1、遍历一个目录:
CFileFind ff;
if(strUDDir.Right(1) != "//")strUDDir += "//";
strUDDir += "*.*";
BOOL res = ff.FindFile(strUDDir);
while(res)
{
res = ff.FindNextFile();
// 不遍历子目录
if(!ff.IsDirectory() && !ff.IsDots())
{
…// 在这里写需要的代码
}
}
ff.Close(); // 不要忘记关闭
2、成员函数的使用
于不常使用CFileFind类的人,对GetfilePath()和GetFileName()等函数得到的值很容易混淆,我写了一段代码,看执行后的结果便可知道各函数返回的结果(看不懂没关系,后面还有个例子)。
l_strFilePath = ff.GetFilePath();
l_strFileName = ff.GetFileName();
l_nPoint = l_strFileName.ReverseFind('.'); // 因为文件名中可能出现多个'.'所以用 ReverseFind而不用Find?
l_nLength = l_strFileName.GetLength();
l_strFileExt = l_strFileName.Right(l_nLength - l_nPoint - 1);
l_strFileTitle = ff.GetFileTitle();
l_strFileUrl = ff.GetFileURL();
l_strFileRoot = ff.GetRoot();
l_dwLength = ff.GetLength();
得到的结果:
Filepath: f:/hoho/hzyong2008.doc
FileName: hzyong2008.doc
FileExe: doc
nFileTitle: hzyong2008
FileUrl: file://f:/hoho/hzyong2008.doc
FileRoot: f:/hoho
FileLength: 603648
对照代码与上面的结果便可以知道各个函数的功能了吧!还有些成员函数没介绍比如GetLastWriteTime(CTime&refTime ),自己慢慢体会去吧。
3、文件备份
TRY
{
CopyFile(strFullName, strBackDir + strFileName, FALSE); // copy file
DeleteFile(strFullName); // delete source file
}
CATCH (CFileException, pEx)
{
AfxMessageBox("UD文件备份失败");
}
END_CATCH
4、附
我写了段代码做了个小试验来试用上面介绍到的函数:主要代码与执行结果如下:
CFileFind ff;
CString l_strFilePath;
CString l_strFileName;
CString l_strFileExt;
CString l_strFileTitle;
CString l_strFileUrl;
CString l_strFileRoot;
DWORD l_dwLength;
CString l_strResult;
int l_nPoint;
int l_nLength;
m_strResult = "";
CString l_strDir = m_strDir; // m_strDir = "f://hoho";
if(l_strDir.Right(1) != "//")
l_strDir += "//";
l_strDir += "*.*";
BOOL res = ff.FindFile(l_strDir);
while(res)
{
res = ff.FindNextFile();
// 不遍历子目录
if(!ff.IsDirectory() && !ff.IsDots())
{
l_strFilePath = ff.GetFilePath();
l_strFileName = ff.GetFileName();
l_nPoint = l_strFileName.ReverseFind('.'); // 因为文件名中可能出现多个'.'所以用ReverseFind而不用Find?
l_nLength = l_strFileName.GetLength();
l_strFileExt = l_strFileName.Right(l_nLength - l_nPoint - 1);
l_strFileTitle = ff.GetFileTitle();
l_strFileUrl = ff.GetFileURL();
l_strFileRoot = ff.GetRoot();
l_dwLength = ff.GetLength();
l_strResult.Format("Filepath: %s/r/nFileName: %s/r/nFileExe: %s/r/nnFileTitle: %s/r/nFileUrl: %s/r/nFileRoot: %s/r/nFileLength: %d/r/n/r/n", l_strFilePath, l_strFileName, l_strFileExt, l_strFileTitle, l_strFileUrl, l_strFileRoot, l_dwLength);
m_strResult += l_strResult;
}
}
ff.Close();