现在的位置: 首页 > 综合 > 正文

递归遍历某一路径下的所有文件(for windows or linux)

2013年10月01日 ⁄ 综合 ⁄ 共 2458字 ⁄ 字号 评论关闭

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

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

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

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

#include <stddef.h>

#include <stdio.h>

#include <sys/types.h>

#include <sys/stat.h>       // stat 函数所在的文件

#include <dirent.h>

//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);
}

 

抱歉!评论已关闭.