How to read filenames from a folder

6 01 2010



How can we read the names of all files in a folder with a specific extension?



Windows has following APIs FindFirstFile and FindNextFile to get the handle of all files in a folder and thus it can extract the relevant information of a file to a WIN32_FIND_DATA structure.



bool FindFilesFromFolder()
   HANDLE            hFile;
   WIN32_FIND_DATA   FindFileData;
   std::vector fileList;

   char chFolderpath[_MAX_PATH];
   CString strExtension   = _T("*.txt");

   strcpy(chFolderpath, _T("D:\\san\\"));
   strcat(chFolderpath, strExtension);

   hFile = FindFirstFile(chFolderpath, &FindFileData);

   if (hFile == INVALID_HANDLE_VALUE) {

      AfxMessageBox(_T("Inavlid file handle."));
      return false;

   CString filepath;


      filepath.Format(_T("%s%s"), _T("D:\\san\\"), FindFileData.cFileName);

   } while(FindNextFile(hFile, &FindFileData));

   return true;



If you want to get all files from a folder irrespective of its extension then just use *.* as filter.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: