Astonish Arts  > AADS  > MFC  > CFileFind

Astonish Arts Developer Section

MFC

CFileFind

ディレクトリ内のファイル/フォルダを列挙する。

ディレクトリ内のファイル/フォルダを列挙する方法を解説します。
ファイルの列挙を行うためには、CFileFindクラスを使用します。
下の例では、ファイル名とディレクトリ名をすべて列挙します。
void EnumFiles(
  CStringArray*	pOutFiles,	// ファイルの相対パス
  CStringArray*	pOutFolders,	// フォルダの相対パス
  CString	strRootPath,	// 検索開始のルートパス
  CString	strStartPath	// ファイルを検索するパス
)
{
  // +--- 検索ターゲットを作成(すべてのファイルをターゲットにする)
  CString	strFindTarget	= strStartPath + L"\\*.*";

  // +--- 最初のファイルを検索
  CFileFind	finder;
  BOOL		bNoEnd = finder.FindFile( strFindTarget );

  // +------------------------------------------------
  // ファイルが終わらない間検索する
  while ( bNoEnd ){

    // +--- 次のファイルを検索
    bNoEnd = finder.FindNextFile();

    // +--- "."か".."は、今の階層、前の階層なので無視
    if ( finder.IsDots() )
      continue ;

    // +--- ディレクトリが見つかった!
    if ( finder.IsDirectory() )
    {
      // +--- パスを取得する
      CString	strFilePath = finder.GetFilePath();

      // +------------------------------------------------
      // ディレクトリリストにディレクトリを追加する
      int		nDirNum	= pOutFolders->GetCount();
      CString	strAdd	= strFilePath.Mid( strRootPath.GetLength() );
      BOOL	bFound	= FALSE;

      // +--- 先頭から登録されているものをチェックする
      for ( int i = 0; i < nDirNum; i++ ){

        // +--- 同じものがすでに登録されている
        if ( pOutFolders->GetAt( (INT_PTR)i ) == strAdd )
        {
          bFound = TRUE;
          break;
        }
      }

      // +--- まだ見つかっていなかった
      if ( bFound == FALSE )
      {
        // +--- 登録する
        pOutFolders->Add( strAdd );
      }

      // +--- 次の階層のファイルを探す
      EnumFiles( 
        pOutFiles,
        pOutFolders,
        strRootPath,
        strFilePath
      );
    }

    // +--- ファイルが見つかった!
    else
    {
      // +------------------------------------------------
      // ファイル情報を追加する
      // +--- ルートからの相対パスを取得する
      CString strFilePath	= finder.GetFilePath().Mid(
        strRootPath.GetLength()
      );

      pOutFiles->Add( strFilePath );

    }
  }
}
			
この関数の使用方法は以下の通りになります。
<使用例>
void main( void )
{
  CStringArray astrFolders;
  CStringArray astrFiles;
  CString strStart = L"C:\\WORKSPACE";

  // +--- strStart 以下のファイル、フォルダを取得します。
  EnumFiles( &astrFiles, &astrFolders, strStart, strStart );
  // astrFiles と astrFolders には strStart からの相対パスが入ります。
  // 絶対パスが必要な場合は strStart + astrFiles.GetAt( 0 ); など、合成する必要があります。
}
			
コピーライト