_findfirst、_findnext、_findclose
指定したパス以下のファイルを検索するプログラム
#pragma warning(disable:4786)
#include <io.h>
#include <vector>
#include <string>
using namespace std;
typedef vector<string> _dirque;
//----------------------------------------------------------
void Search( _dirque &que )
{
// このサブルーチンはキューにパスが入っている限り呼ばれつづける
// _finddata_t構造体は_findfirstおよび_findnextが返すファイル属性情報を格納する
_finddata_t findData;
long hFile; // 戻り値用
_dirque::iterator it; // イテレータ定義
string dirPath = que.at(0); // キューの先頭を取得
it = que.begin(); // 先頭を取得
que.erase(it); // 先頭を詰める
string targetPath = dirPath + "\\*.*"; // ディレクトリも含めて検索
printf( "検索中 ⇒ %s\n", targetPath.c_str() );
if ( ( hFile = _findfirst( targetPath.c_str(), &findData ) ) == -1L ) {
printf( "Not found in target directory\n" );
return;
}
while ( _findnext( hFile, &findData ) == 0 ) {
// 1文字目が"."".."とかは無視して続行
if( findData.name[0] == '.' ) continue;
// 見つかった名前を連結して新しいパスを作成
string newPath = dirPath + "\\" + findData.name;
if ( findData.attrib & _A_SUBDIR ) {
que.push_back( newPath ); // 検索パスを追加
printf( "フォルダが見つかりました ⇒ %s\n", newPath.c_str() );
} else {
printf( "ファイルが見つかりました ⇒ %s\n", newPath.c_str() );
}
}
_findclose( hFile );
}
//----------------------------------------------------------
int main( int argc, char **argv )
{
// 引数チェック
if ( argc != 2 ) {
printf( "引数の数が正しくありません\n" );
exit( 1 );
}
printf( "検索開始パス ⇒ %s\n", argv[1] );
_dirque que; // キュー配列を定義
que.push_back( argv[1] );
// 検索処理
while ( que.size() )
Search( que );
return 0;
}
Comments