+ -
当前位置:首页 → 问答吧 → 这个递归错在哪

这个递归错在哪

时间:2010-08-21

来源:互联网

  1. #include <sys/types.h>
  2. #include <stdio.h>
  3. #include <dirent.h>
  4. #include <string.h>
  5. #include <sys/stat.h>



  6. void search(DIR * p_parent, const char *src)
  7. {
  8.         struct dirent *p_file;
  9.         struct stat statbuf;
  10.         char *dirname;
  11.         while((p_file=readdir(p_parent)) != NULL)
  12.         {
  13.                 stat(p_file->d_name, &statbuf);
  14.                 if (S_ISREG(statbuf.st_mode))
  15.                 {
  16.                 //        if(strstr(p_file->d_name, src) != NULL)
  17.                                 printf("regular file: %s\n", p_file->d_name);
  18.                 }
  19.                 else if (S_ISDIR(statbuf.st_mode))
  20.                 {
  21.                         printf("directory: %s\n", p_file->d_name);
  22.                         if (strcmp(p_file->d_name,".") != 0 && strcmp(p_file->d_name, "..") != 0)
  23.                         {
  24.                                 search(opendir(p_file->d_name), src);
  25.                         }
  26.                 }
  27.         }
  28.         closedir(p_parent);
  29. }

  30. int main(int argc, char **argv)
  31. {
  32.         DIR *p_dir;
  33.         struct dirent * p_file;
  34.         if (argc != 2)
  35.         {
  36.                 fprintf(stderr, "Usage: %s dirname", argv[1]);
  37.                 return 1;
  38.         }
  39.         p_dir = opendir(argv[1]);
  40.         if (p_dir == NULL)
  41.         {
  42.                 fprintf(stderr, "opendir error!\n");
  43.                 return 1;
  44.         }
  45.         search(p_dir, "lrc");
  46.         return 0;
  47. }
复制代码
它会把子目录里的普通文件当成目录处理

作者: kingoftime3   发布时间: 2010-08-21

回复 kingoftime3


    stat的时候应该使用full path

作者: churchmice   发布时间: 2010-08-21