Listing the Files in a Directory The following example calls FindFirstFile, FindNextFile, and FindClose to list the files in a specified directory. Note that the only limitation on the number of files a directory can contain is the storage capacity of the disk. #define _WIN32_WINNT 0x0501#include <windows.h> #include <string.h> #include <stdio.h>int main(int argc, char *argv[]) { WIN32_FIND_DATA FindFileData; HANDLE hFind = INVALID_HANDLE_VALUE; char DirSpec[MAX_PATH]; // directory specification DWORD dwError; printf ("Target directory is %s.\n", argv[1]); strncpy (DirSpec, argv[1], strlen(argv[1])+1); strncat (DirSpec, "\\*", 3); hFind = FindFirstFile(DirSpec, &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { printf ("Invalid file handle. Error is %u\n", GetLastError()); return (-1); } else { printf ("First file name is %s\n", FindFileData.cFileName); while (FindNextFile(hFind, &FindFileData) != 0) { printf ("Next file name is %s\n", FindFileData.cFileName); }
The following example calls FindFirstFile, FindNextFile, and FindClose to list the files in a specified directory.
Note that the only limitation on the number of files a directory can contain is the storage capacity of the disk.
#define _WIN32_WINNT 0x0501#include <windows.h>
#include <string.h>
#include <stdio.h>int main(int argc, char *argv[])
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind = INVALID_HANDLE_VALUE;
char DirSpec[MAX_PATH]; // directory specification
DWORD dwError; printf ("Target directory is %s.\n", argv[1]);
strncpy (DirSpec, argv[1], strlen(argv[1])+1);
strncat (DirSpec, "\\*", 3); hFind = FindFirstFile(DirSpec, &FindFileData); if (hFind == INVALID_HANDLE_VALUE)
{
printf ("Invalid file handle. Error is %u\n", GetLastError());
return (-1);
}
else
{
printf ("First file name is %s\n", FindFileData.cFileName);
while (FindNextFile(hFind, &FindFileData) != 0)
{
printf ("Next file name is %s\n", FindFileData.cFileName);
}
dwError = GetLastError();
if (dwError == ERROR_NO_MORE_FILES)
{
FindClose(hFind);
}
else
{
printf ("FindNextFile error. Error is %u\n", dwError);
return (-1);
}
}
return (0);
}
while( res )
{
res = ff.FindNextFile();
strPath = ff.GetFilePath();
if(ff.IsDirectory() && !ff.IsDots())
TravelDir(strPath); //该对象是个文件夹,利用嵌套来遍历
else if(!ff.IsDirectory() && !ff.IsDots())
{
.... }
}
ff.Close();
BOOL bWorking = finder.FindFile(strWildcard);
while (bWorking)
{
bWorking = finder.FindNextFile(); if (finder.IsDots())
continue;
if (!finder.IsDirectory())
{
CString str = finder.GetFilePath();
MessageBox(str);
}
} finder.Close();