【C】——treeコマンドの実装

6699 ワード

ほとんどのlinuxシステムには使いやすいコマンドがあります.treeは、ディレクトリを表示する構造ですが、FreeBSDにはこのコマンドがないことがわかり、簡単なtreeを実現しました.コードは以下の通りである:主に再帰的な考え方を利用している.
 1 #include <stdio.h>
 2 #include <sys/types.h>
 3 #include <dirent.h>
 4 #include <string.h>
 5 
 6 void show_tree(char *path, int deep) {
 7     DIR *dirp = NULL;
 8     struct dirent *dp = NULL;
 9     int index = deep;
10     char *tmp_path = path;
11 
12     tmp_path = path + strlen(path);
13     *tmp_path++ = '/';
14     *tmp_path = 0;
15 
16     dirp = opendir(path);
17     if (dirp == NULL){
18         printf("can't open dir %s
", path); 19 return ; 20 } 21 while ((dp = readdir(dirp)) != NULL){ 22 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")){ 23 continue; 24 } 25 while(index--) { 26 printf("| "); 27 } 28 printf("|--%s
", dp->d_name); 29 index = deep; 30 strcpy(tmp_path, dp->d_name); 31 if (dp->d_type == 4) 32 show_tree(path, deep + 1); 33 } 34 closedir(dirp); 35 } 36 37 int main(int argc, char *argv[]) { 38 char path[1024] = "."; 39 int deep = 0; 40 41 if (argc == 2) { 42 sprintf(path, "%s", argv[1]); 43 } 44 45 show_tree(path, deep); 46 return 0; 47 }