C ++ MFCを使用して再帰的なファイル検索?
-
06-09-2019 - |
質問
再帰的にC ++とMFCを使用してファイルを検索するためのクリーンな方法は何ですか?
EDIT:これらのソリューションのいずれかが1つのパスを介して複数のフィルタを使用する機能を提供していますか?私はCFileFindで私が*。*フィルタした後、さらに別のファイルタイプにフィルタリングするカスタムコードを記述することができると思います。何のオファーが内蔵されない複数のフィルタ(すなわち。* .EXE、*。DLL)?
EDIT2:ちょうど私はそれが私の前のEDITが無効になります作っていた明白な仮定を実現。私はCFileFindと再帰検索を実行しようとしていた場合は、それ以外のサブディレクトリが一致しませんので、私は私のワイルドカードとして*。*使用する必要がありますし、何の再帰は行われません。だから、別のファイルextentionsをフィルタリングすることは関係なく、個別に処理する必要があります。
解決
使用 CFileFind
するます。
href="http://msdn.microsoft.com/en-us/library/scx99850(VS.80).aspx" rel="noreferrer">例からをこの
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();
}
他のヒント
ブーストのファイルシステムの実装を使用してください!
再帰的な例でも、ファイルシステムのホームページにあるます:
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 のライブラリをチェックアウト - の略で、のREC の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()も、ファイルは
同じdirectory``に存在し、falseを返します