C查找某个目录下的所有文件(包括子目录)(转)

时间:2021-11-25 14:29:59


by:LionD8

//原作者不详,偶然发现。然后稍做了修改,测试了以下。整理了一下。

#include "stdio.h"
#include "windows.h"
#include "winbase.h"
void FindFileInDir(char* rootDir);

main()
{
 FindFileInDir("C://");
}

void FindFileInDir(char* rootDir)//, char* strRet)
{
    char fname[1024];
    ZeroMemory(fname, 1024);
    WIN32_FIND_DATA fd;
    ZeroMemory(&fd, sizeof(WIN32_FIND_DATA));
    HANDLE hSearch;
    char filePathName[256];
    char tmpPath[256];
    ZeroMemory(filePathName, 256);
    ZeroMemory(tmpPath, 256);
    strcpy(filePathName, rootDir);
    BOOL bSearchFinished = FALSE;
    if( filePathName[strlen(filePathName) -1] != '//' )
    {
       strcat(filePathName, "//");
    }
    strcat(filePathName, "*");

    hSearch = FindFirstFile(filePathName, &fd);
 
    //Is directory

    if( (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)

       && strcmp(fd.cFileName, ".") && strcmp(fd.cFileName, "..") )      
    {

       strcpy(tmpPath, rootDir);


       strcat(tmpPath, fd.cFileName);

    if( tmpPath[strlen(tmpPath) -1] != '//' )
  {
   strcat(tmpPath, "//");
  } 
       FindFileInDir(tmpPath);
    }
    while( !bSearchFinished )
    {

       if( FindNextFile(hSearch, &fd) )
       {

           if( (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)

              && strcmp(fd.cFileName, ".") && strcmp(fd.cFileName, "..") )      
           {

              strcpy(tmpPath, rootDir);

              strcat(tmpPath, fd.cFileName);
      if( tmpPath[strlen(tmpPath) -1] != '//' )
    {
     strcat(tmpPath, "//");
    } 

              FindFileInDir(tmpPath);
           }
           else   if( strcmp(fd.cFileName, ".") && strcmp(fd.cFileName, "..") )
                  {
      printf("%s%s/n",rootDir,fd.cFileName);
         
                  }
       }
       else
    {
           if( GetLastError() == ERROR_NO_MORE_FILES )        
           {
              bSearchFinished = TRUE;

           }
           else
              bSearchFinished = TRUE;
       }
    }
    FindClose(hSearch);

}