How To Get Files in a Directory

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
#include
#include
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; } [/sourcecode] 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.

Advertisements

One Response to How To Get Files in a Directory

  1. Zach Rogers says:

    Thank you very much, this has helped me with a current project that I am working on.

    Thanks,
    ZachR.

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: