CFileFind遍历目录查找文件

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值