I'm trying to write code that searches through a folder and retrieves the names of the files in the folder.
So far I have the following code. When I run it, I just keep getting the Usage portion of the code. Why does argc need to be equal to 2 for the code to not print the usage portion. Also, where in the code would I specify the name of the directory I want to search?
Code:
#define _WIN32_WINNT 0x0501
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
#include <conio.h>
int _tmain(int argc, TCHAR *argv[])
{
WIN32_FIND_DATA ffd;
TCHAR 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)
{
_tprintf(TEXT("Usage: %s <dir>\n"), argv[0]);
return (-1);
}
// Check that the input path plus 2 is not longer than MAX_PATH.
StringCchLength(argv[1], MAX_PATH, &length_of_arg);
if (length_of_arg > (MAX_PATH - 2))
{
_tprintf(TEXT("Directory path is too long.\n"));
return (-1);
}
_tprintf (TEXT("Target 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, TEXT("\\*"));
// Find the first file in the directory.
hFind = FindFirstFile(szDir, &ffd);
if (INVALID_HANDLE_VALUE == hFind)
{
dwError = GetLastError();
_tprintf (TEXT("FindFirstFile failed (%u)\n"), dwError);
return dwError;
}
else
{
_tprintf (TEXT("First file: %s\n"), ffd.cFileName);
// List all the other files in the directory.
while (FindNextFile(hFind, &ffd) != 0)
{
_tprintf (TEXT(" Next file: %s\n"), ffd.cFileName);
}
dwError = GetLastError();
if (dwError != ERROR_NO_MORE_FILES)
{
_tprintf (TEXT("FindNextFile error (%u)\n"), dwError);
goto Cleanup;
}
}
Cleanup:
FindClose(hFind);
return dwError;
}