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;

   do
   {

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

   } 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.

Advertisements

Actions

Information

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: