Program Diary -2
linux/unix下命令行开关与环境变量

linux/unix目录操作的实例

perhong posted @ 2008年5月11日 20:54 in C with tags c linux unix , 1960 阅读

目录扫描程序:

  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <dirent.h>
  4.  
  5. #include <string.h>
  6. #include <sys/stat.h>
  7. #include <stdlib.h>
  8.  
  9.  
  10. void printdir(char *dir, int depth);
  11.  
  12.  
  13. int main(int argc, char* argv[])
  14. {
  15.         char *topdir = ".";
  16.         if (argc >= 2)
  17.                 topdir = argv[1];
  18.  
  19.         printf("Dirrctory scan of %s\n", topdir);
  20.         printdir(topdir, 0);
  21.         printf("done.\n");
  22.  
  23.         exit(0);
  24. }
  25.  
  26.  
  27. void printdir(char *dir, int depth)
  28. {
  29.         DIR *dp;
  30.         struct stat statbuf;
  31.         struct dirent *entry;
  32.  
  33.         if ((dp = opendir(dir)) == NULL) {
  34.                 fprintf(stderr, "cannot open directory : %s\n", dir);
  35.                 return;
  36.         }
  37.         chdir(dir);
  38.         while ((entry = readdir(dp)) != NULL) {
  39.                 lstat(entry->d_name, &statbuf);
  40.                 if (S_ISDIR(statbuf.st_mode)) {
  41.                         if (strcmp(".", entry->d_name) == 0 ||
  42.                                 strcmp("..", entry->d_name) == 0)
  43.                                 continue;
  44.                         printf("%*s%s/\n", depth,"", entry->d_name);
  45.                         printdir(entry->d_name, depth+4);
  46.                 }
  47.                 else printf("%*s%s\n", depth,"", entry->d_name);
  48.         }
  49.         chdir("..");
  50.         closedir(dp);   
  51. }
  52.  
  53.  

总结:

1.printf%*s的应用

2.递归应用

程序运行截图:


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter