使用 C++ MFC 进行递归文件搜索?

2021-12-16 00:00:00 递归 c++ mfc file-search

使用 C++ 和 MFC 递归搜索文件的最简洁方法是什么?

What is the cleanest way to recursively search for files using C++ and MFC?

这些解决方案中的任何一个都提供通过一次通过使用多个过滤器的能力吗?我想使用 CFileFind 我可以过滤 *.* 然后编写自定义代码以进一步过滤到不同的文件类型.是否提供内置的多个过滤器(即 *.exe、*.dll)?

Do any of these solutions offer the ability to use multiple filters through one pass? I guess with CFileFind I could filter on *.* and then write custom code to further filter into different file types. Does anything offer built-in multiple filters (ie. *.exe,*.dll)?

刚刚意识到我所做的一个明显假设使我之前的 EDIT 无效.如果我尝试使用 CFileFind 进行递归搜索,我必须使用 *.* 作为我的通配符,否则将无法匹配子目录并且不会发生递归.因此,无论如何都必须单独处理对不同文件扩展名的过滤.

Just realized an obvious assumption that I was making that makes my previous EDIT invalid. If I am trying to do a recursive search with CFileFind, I have to use *.* as my wildcard because otherwise subdirectories won't be matched and no recursion will take place. So filtering on different file-extentions will have to be handled separately regardless.

推荐答案

使用 CFileFind.

看看这个示例来自MSDN:

Take a look at this example from MSDN:

void Recurse(LPCTSTR pstr)
{
   CFileFind finder;

   // build a string with wildcards
   CString strWildcard(pstr);
   strWildcard += _T("\*.*");

   // start working for files
   BOOL bWorking = finder.FindFile(strWildcard);

   while (bWorking)
   {
      bWorking = finder.FindNextFile();

      // skip . and .. files; otherwise, we'd
      // recur infinitely!

      if (finder.IsDots())
         continue;

      // if it's a directory, recursively search it

      if (finder.IsDirectory())
      {
         CString str = finder.GetFilePath();
         cout << (LPCTSTR) str << endl;
         Recurse(str);
      }
   }

   finder.Close();
}

相关文章