Windows Directory Management 4

 

 

 

 

 

Listing the Files in a Directory Program Example

 

The following program example calls FindFirstFile(), FindNextFile(), and FindClose() to list files in a specified directory.

Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed.

 

Listing the Files in a Directory Program Example: Creating new Win32 C++ console application project in Visual C++ .NET

 

Then, add the source file and give it a suitable name.

Next, add the following source code.

 

#include <windows.h>

#include <stdio.h>

// For StringCchLength(), StringCchCopy(), StringCchCat(),

// StringCchPrintf() - safer versions

#include <strsafe.h>

 

// A prototype that receives a function name, displaying

// system error code and its respective message

void DisplayErrorBox(LPTSTR lpszFunction);

 

int wmain(int argc, WCHAR *argv[])

{

   WIN32_FIND_DATA ffd;

   LARGE_INTEGER filesize;

   WCHAR szDir[MAX_PATH];

   size_t length_of_arg;

   HANDLE hFind = INVALID_HANDLE_VALUE;

   DWORD dwError=0;

  

   // If the directory is not specified as a command-line argument, print usage

   if(argc != 2)

   {

      wprintf(L"\nUsage: %s <directory name>\n", argv[0]);

      return (-1);

   }

 

   // Check that the input path plus 3 is not longer than MAX_PATH.

   // Three characters are for the "\*" plus NULL appended below

   StringCchLength(argv[1], MAX_PATH, &length_of_arg);

 

   if (length_of_arg > (MAX_PATH - 3))

   {

      wprintf(L"\nDirectory path is too long.\n");

      return (-1);

   }

 

   wprintf(L"\nTarget directory is %s\n\n", argv[1]);

 

   // Prepare string for use with FindFile() functions.  First, copy the

   // string to a buffer, then append '\*' to the directory name

   StringCchCopy(szDir, MAX_PATH, argv[1]);

   StringCchCat(szDir, MAX_PATH, L"\\*");

 

   // Find the first file in the directory

   hFind = FindFirstFile(szDir, &ffd);

 

   if (INVALID_HANDLE_VALUE == hFind)

   {

      DisplayErrorBox(L"FindFirstFile()");

      return dwError;

   }

  

   // List all the files in the directory with some info about them

   do

   {

      if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)

      {

         wprintf(L"  %s   <DIR>\n", ffd.cFileName);

      }

      else

      {

         filesize.LowPart = ffd.nFileSizeLow;

         filesize.HighPart = ffd.nFileSizeHigh;

         wprintf(L"           %s          %ld bytes\n", ffd.cFileName, filesize.QuadPart);

      }

   }

   while (FindNextFile(hFind, &ffd) != 0);

 

   dwError = GetLastError();

   if (dwError != ERROR_NO_MORE_FILES)

   {

      DisplayErrorBox(L"FindFirstFile()");

   }

 

   FindClose(hFind);

   return dwError;

}

 

void DisplayErrorBox(LPTSTR lpszFunction)

{

    // Retrieve the system error message for the last-error code

    LPVOID lpMsgBuf;

    LPVOID lpDisplayBuf;

    DWORD dw = GetLastError();

 

    FormatMessage(

        FORMAT_MESSAGE_ALLOCATE_BUFFER |

        FORMAT_MESSAGE_FROM_SYSTEM |

        FORMAT_MESSAGE_IGNORE_INSERTS,

        NULL,

        dw,

        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),

        (LPTSTR) &lpMsgBuf,

        0, NULL );

 

    // Display the error message and clean up

    lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(WCHAR));

    StringCchPrintf((LPTSTR)lpDisplayBuf, LocalSize(lpDisplayBuf) / sizeof(WCHAR),  L"%s failed with error %d: %s", lpszFunction, dw, lpMsgBuf);

    MessageBox(NULL, (LPCTSTR)lpDisplayBuf, L"Error", MB_OK);

 

    LocalFree(lpMsgBuf);

    LocalFree(lpDisplayBuf);

}

 

Build and run the project. The following screenshots are sample outputs.

 

Listing the Files in a Directory Program Example: A sample console program output in action 1

 

Listing the Files in a Directory Program Example: A sample console program output in action 2

 

Listing the Files in a Directory Program Example: A sample console program output in action 3

 

Listing the Files in a Directory Program Example: A sample console program output in action 4

 

 

 

 

< Windows Directory 3 | Win32 Programming | Win32 Directory Index | Windows Directory 5 >