文章收藏-FAQ 位置:电脑学习网

递归遍历某一路径下的所有文件

    在windows下,可以使用FindFirstFile和FindNextFile来实现。

    而在Linux下,则可以使用opendir和readdir来实现。

    具体实现见下面两个函数,分别实现了打印某一路径下的所有文件,包括子目录下的文件。在具体实现的时候需要注意设置路径。

注:
    下面两个程序都通过编译通过,且正常执行。
    windows下使用VC6.0编译;Linux下使用gcc 3.4.3编译。

//for windows
void findAllFile(char * pFilePath)
{

 WIN32_FIND_DATA FindFileData;
 HANDLE hFind = INVALID_HANDLE_VALUE;
 char DirSpec[MAX_PATH + 1];  // directory specification
 DWORD dwError;

 strncpy (DirSpec, pFilePath, strlen(pFilePath) + 1);
 SetCurrentDirectory(pFilePath);
 strncat (DirSpec, “\\*“, 3);

 hFind = FindFirstFile(DirSpec, &FindFileData);

 if (hFind == INVALID_HANDLE_VALUE)
 {
  printf (“Invalid file handle. Error is %u\n“, GetLastError());
  return ;
 }
 else
 {
  if (FindFileData.dwFileAttributes != FILE_ATTRIBUTE_DIRECTORY )
  {
   printf (“    %s\n“, FindFileData.cFileName);
  }
  else if(FindFileData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY
   && strcmp(FindFileData.cFileName, “.“) != 0
   && strcmp(FindFileData.cFileName, “..“) != 0)
  {
   char Dir[MAX_PATH + 1];
   strcpy(Dir, pFilePath);
   strncat(Dir, “\\“, 2);
   strcat(Dir, FindFileData.cFileName);

   findAllFile(Dir);
  }

  while (FindNextFile(hFind, &FindFileData) != 0)
  {
   if (FindFileData.dwFileAttributes != FILE_ATTRIBUTE_DIRECTORY)
   {
    printf (“    %s\n“, FindFileData.cFileName);
   }
   else if(FindFileData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY
    && strcmp(FindFileData.cFileName, “.“) != 0
    && strcmp(FindFileData.cFileName, “..“) != 0)
   {
    char Dir[MAX_PATH + 1];
    strcpy(Dir, pFilePath);
    strncat(Dir, “\\“, 2);
    strcat(Dir, FindFileData.cFileName);
    findAllFile(Dir);
   }

  }

  dwError = GetLastError();
  FindClose(hFind);
  if (dwError != ERROR_NO_MORE_FILES)
  {
   printf (“FindNextFile error. Error is %u\n“, dwError);
   return;
  }
 }
}


//for linux
void findAllFile(char * pFilePath)
{
 DIR * dir;
 dirent * ptr;
 struct stat stStatBuf;
 chdir(pFilePath);
        dir = opendir(pFilePath);
 while ((ptr = readdir(dir)) != NULL)
     {
  if (stat(ptr-〉d_name, &stStatBuf) == -1)
  {
   printf(“Get the stat error on file:%s\n“, ptr-〉d_name);
   continue;
  }
  if ((stStatBuf.st_mode & S_IFDIR) && strcmp(ptr-〉d_name, “.“) != 0
    && strcmp(ptr-〉d_name, “..“) != 0)
  {
   char Path[MAX_PATH];
   strcpy(Path, pFilePath);
   strncat(Path, “/“, 1);
   strcat(Path, ptr-〉d_name);
   findAllFile(Path);
  }
  if (stStatBuf.st_mode & S_IFREG)
  {
   printf(“  %s\n“, ptr-〉d_name);
  }
  //this must change the directory , for maybe changed in the recured

function
  chdir(pFilePath);
 }
     closedir(dir);
}

     [文章来源:“十万个为什么”电脑学习网]
     [网络地址:http://why100000.com]
     [版权声明:除本站部分特别声明禁止转载的专稿外,其他的文章可以自由转载,但请务必注明出处和原始作者。本站文章版权归文章原作者所有。如果本站转载的文章有版权问题请联系本站,我们会尽快予以更正。]
 

【字体:[大] [中] [小] 【加入收藏】 【发表评论】 【关闭本窗口】

Copyright © “十万个为什么”电脑学习网 2000-2007 陕ICP备06007929号
站务联系:MSN & Email:zhangking2008@gmail.com  QQ:9365822