现在的位置: 首页 > 综合 > 正文

VS2010 实现文件夹浏览、遍历所有文件

2013年10月08日 ⁄ 综合 ⁄ 共 1397字 ⁄ 字号 评论关闭

    最近开始写一个隐秘图像特征提取的工程,第一步就是要实现:打开一个文件夹,获得所有图像文件的数目和列表。发现VS2010实现文件夹浏览可以不再使用SHBrowseForFolder ,使用CShellManager::BrowseForFolde更方便快捷。代码如下:

 

1、浏览文件夹:

Cstring strPathName;

if (!theApp.GetShellManager()->BrowseForFolder (strPathName,
  this, strPathName, _T("选择图片所在文件夹")))
 {
  AfxMessageBox(_T("未选中文件夹"));
  return;
 }
 //在文本控件里显示选择的路径

GetDlgItem(IDC_EDIT_PATH)->SetWindowTextA(strPathName); 

 

注意:theApp是一个MFC应用程序类的一个对象,每一个应用程序都有这样的一个对象,他的作用主要是将你所创建的应用程序与底层的函数联系起来,在创立theAPP时通过this指针把MFC的WinMain函数联系起来。

这里如果要使用GetShellManager(),必须修改C**App类继承的父类,由CWinApp改为CWinAppEx;

 

2、遍历所有文件:

 CString strPathName;
 GetDlgItem(IDC_EDIT_PATH)->GetWindowText(strPathName);
 if (strPathName.IsEmpty())
 {
  AfxMessageBox(_T("请选择图片所在的文件夹!"));
 } 
 strPathName +="//*.*";
 CFileFind finder;
 CStringList filelist;//文件列
 unsigned long filenum=0;
 BOOL bResult=finder.FindFile(strPathName);

 if(!bResult)
 {
  AfxMessageBox(_T("未找到图像文件!"));
  return;
 }

 while (bResult)
 {
  bResult = finder.FindNextFile();
  //判断是否是目录或者是隐藏文件,又或者是".."和".",如果是,进入下一轮循环
  if(finder.IsDirectory()|| finder.IsDots() || finder.IsHidden())
   continue;
  else//如果是文件
  {
   CString str;
   //得到文件名
   str = finder.GetFileName();
   //得到文件后缀名
   int nLen = str.GetLength() - finder.GetFileTitle().GetLength();
   str = str.Right(nLen);
   //判断文件格式,如果是图像文件,将其完整的路径保存在列表中
   if(str == ".jpg" || str == ".png" || str == ".bmp" || str == ".gif")
    filelist.AddTail(finder.GetFilePath());
  }
 }
 finder.Close();
 filenum=filelist.GetCount();

抱歉!评论已关闭.