How To Get Files in a Directory

September 17, 2008

VC++ provides two API’s FindFirstFile and FindNextFile to get files in a directory. You can specify the file name(s) to be searched in terms of wild cards as well to match your criteria. See the following example.

#include<iostream>
#include<string>
#include<wtypes.h>
using namespace std;

int main()
{  
   HANDLE FindHandle = INVALID_HANDLE_VALUE;
   WIN32_FIND_DATA FindData;
   string FileName = ".\\*.*";   // . specifies the current directory
   FindHandle = FindFirstFile(FileName.c_str(), &FindData);
   if (INVALID_HANDLE_VALUE != FindHandle)
   {
      do
      {
         cout << FindData.cFileName << '\n';        
      } while (FindNextFile(FindHandle, &FindData) != 0);
      FindClose(FindHandle);
   }
   return 0;
}

You can call the GetLastError() function to see why the while loop has finished. If the result of GetLastError() is ERROR_NO_MORE_FILES, there is no more file matching the criteria in the specified directory and hence it is not an unexpected error.