设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
查看: 33895|回复: 0
打印 上一主题 下一主题

【每日一坑 4】 查找文件

[复制链接]

0

主题

0

好友

79

积分

注册会员

Rank: 2

楼主
发表于 2013-12-21 01:59:29 |显示全部楼层
长长的c又来了,有点乱没来得急整理。。。
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. #include <dirent.h>
  5. #include <errno.h>
  6. #include <string.h>
  7. #include <sys/stat.h>

  8. #define PATH_SIZE 4096

  9. char *path;

  10. int show_txt(char *);

  11. int main(int argc, const char *argv[])
  12. {
  13.   if (argc != 2) {
  14.     printf("Usage: ./a.out <path of dir>\n");
  15.     exit(1);
  16.   }

  17.   path = malloc(PATH_SIZE);
  18.   strcpy(path, argv[1]);

  19.   show_txt(path);

  20.   free(path);

  21.   return 0;
  22. }

  23. int show_txt(char *path)
  24. {
  25.   struct stat statbuf;
  26.   struct dirent *dirp;
  27.   DIR *dp;
  28.   char *ptr;

  29.   int len = strlen(path);

  30.   if (lstat(path, &statbuf) < 0) {  /* lstat error */
  31.     perror("lstat error");
  32.     exit(1);
  33.   }

  34.   if (S_ISDIR(statbuf.st_mode) == 0) {  /* not a directory */
  35.       if (strcmp(&path[len-4], ".txt") == 0) {
  36.       printf("%s\n", path);
  37.     }
  38.     return 0;
  39.   }

  40.   ptr = path + len;
  41.   *ptr++ = '/';
  42.   *ptr = 0;

  43.   if ((dp = opendir(path)) == NULL) { /* open directory error */
  44.     perror("opendir error");
  45.     exit(1);
  46.   }

  47.   /* iterate the directory(dp)'s each element*/
  48.   while ((dirp = readdir(dp)) != NULL) {  
  49.     /* ignore the present directory and the last directory */
  50.     if (strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..") == 0)
  51.       continue;

  52.     strcpy(ptr, dirp->d_name);  /* append the element's name to path */
  53.     show_txt(path); /* call the show_txt(char*) recursively */
  54.   }

  55.   ptr[-1] = 0;
  56.   closedir(dp);
  57.   return 0;
  58. }
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-5-3 01:11 , Processed in 0.025770 second(s), 23 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部