본문 바로가기

개발/Client Side

[MFC] 디렉토리 recursive 탐색 소스 코드

첫번째 예제
void __stdcall EnumDirectory(LPCTSTR lpPath)
{
 if(lpPath == NULL)
  return ;
 
 TCHAR szPath[560] = {0, };
 wsprintf(szPath, _T("%s"), lpPath);
 if(szPath[_tcslen(szPath) - 1] == '\\')
  szPath[_tcslen(szPath) - 1] = NULL;
 
 TCHAR szFindPath[560] = {0, };
 wsprintf(szFindPath, _T("%s\\*.*"), szPath);
 
 WIN32_FIND_DATA wfd;
 ZeroMemory(&wfd, sizeof(WIN32_FIND_DATA));
 
 TCHAR szFilePath[560] = {0, };
 HANDLE h = FindFirstFile(szFindPath, &wfd);
 if(h == INVALID_HANDLE_VALUE)
  return ;
 
 do{
  ZeroMemory(szFilePath, sizeof(szFilePath) / sizeof(TCHAR));
  wsprintf(szFilePath, _T("%s\\%s"), szPath, wfd.cFileName);
  
  if( (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY )
  {
   if(wfd.cFileName[0] != '.' && wfd.cFileName[1] != '.')
    EnumDirectory(szFilePath);
  }
  else
  {
    /*
    File......
    */
  }
 }while(FindNextFile(h, &wfd));
 
 FindClose(h);
}



두번째 예제
class CFoo
{
  //...
  // Operations
public:
  static void SearchDirectory(LPCTSTR pszRootPath,
                               CStringArray& arrFiles,
                               bool bRecursive = true);
  //...
};

void CFoo::SearchDirectory(LPCTSTR pszRootPath, 
                           CStringArray& arrFiles,
                           bool bRecursive /*= true*/)
{
  CString strToFind;
  strToFind.Format(_T("%s\\*.*"), pszRootPath);
   
  CFileFind ff;
  BOOL bFound = ff.FindFile(strToFind);
  while(bFound)
  {
    bFound = ff.FindNextFile();
    if(ff.IsDirectory() && !ff.IsDots())
    {
      if(true == bRecursive)
      {
        CString strRootPath = ff.GetFilePath();
        SearchDirectory(strRootPath, arrFiles, bRecursive);
      }
    }
    else if(!ff.IsDots() && !ff.IsDirectory())
    {
      CString strFilePath = ff.GetFilePath();
      arrFiles.Add(strFilePath);
    }
  }
}

void CWhateverFoo::WhateverFunction() 
{
  //...
  CStringArray arrFiles;
  CFoo::SearchDirectory(_T("c:\\Images"), arrFiles);
  //...    
}