用C ++ MFC递归文件搜索?
-
06-09-2019 - |
题
什么是用C ++和对文件的递归搜索的干净的方式MFC?
编辑:是否有任何这些解决方案通过提供一个通过使用多个过滤器的能力吗?我想用CFileFind我可以过滤对*。*然后编写自定义代码,以进一步筛选成不同的文件类型。做任何事情提供内置多个过滤器(即* .EXE,*。dll的)?
EDIT2:只是意识到,我正在做一个让我以前的EDIT无效明显假设。如果我试图做CFileFind递归搜索,我必须使用*。*我的通配符,否则子目录会不匹配,并没有递归将举行。等不同的文件的一些推广滤波将具有无论要分开处理。
解决方案
使用 CFileFind
。
看看这个例如从的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();
}
其他提示
使用 Boost的文件系统实现!
在递归的例子是即使在文件系统中的主页:
bool find_file( const path & dir_path, // in this directory,
const std::string & file_name, // search for this name,
path & path_found ) // placing path here if found
{
if ( !exists( dir_path ) ) return false;
directory_iterator end_itr; // default construction yields past-the-end
for ( directory_iterator itr( dir_path );
itr != end_itr;
++itr )
{
if ( is_directory(itr->status()) )
{
if ( find_file( itr->path(), file_name, path_found ) ) return true;
}
else if ( itr->leaf() == file_name ) // see below
{
path_found = itr->path();
return true;
}
}
return false;
}
我知道这是不是你的问题,但它也很容易,而无需通过递归使用CStringArray
void FindFiles(CString srcFolder)
{
CStringArray dirs;
dirs.Add(srcFolder + "\\*.*");
while(dirs.GetSize() > 0) {
CString dir = dirs.GetAt(0);
dirs.RemoveAt(0);
CFileFind ff;
BOOL good = ff.FindFile(dir);
while(good) {
good = ff.FindNextFile();
if(!ff.IsDots()) {
if(!ff.IsDirectory()) {
//process file
} else {
//new directory (and not . or ..)
dirs.InsertAt(0,nd + "\\*.*");
}
}
}
ff.Close();
}
}
查看 recls 库 - 代表的录制的ursive的 LS 的 - 这是一个递归搜索库,UNIX和Windows的作品。这是一个C库,以适应不同的语言,包括C ++。从内存中,你可以使用它像以下内容:
using recls::search_sequence;
CString dir = "C:\\mydir";
CString patterns = "*.doc;abc*.xls";
CStringArray paths;
search_sequence files(dir, patterns, recls::RECURSIVE);
for(search_sequence::const_iterator b = files.begin(); b != files.end(); b++) {
paths.Add((*b).c_str());
}
这会发现所有.doc文件,并用C与ABC开头的所有.xls文件:\ MYDIR或任何子目录
我没有编这一点,但它应该是相当接近大关。
CString strNextFileName , strSaveLog= "C:\\mydir";
Find.FindFile(strSaveLog);
BOOL l = Find.FindNextFile();
if(!l)
MessageBox("");
strNextFileName = Find.GetFileName();
其不工作。 Find.FindNextFile()返回false甚至文件都存在于相同的directory``
不隶属于 StackOverflow