zoukankan      html  css  js  c++  java
  • 【C】——实现tree命令

      在大部分的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 }
  • 相关阅读:
    RegularExpression 2
    Python __str__() and __repr()__
    RegularExpression 1
    python new kill callback
    Generic Programming v1
    spring的@Transactional注解详细用法
    cmd批量打开网页和关闭网页的批处理代码
    windows批处理中实现延时的办法
    单元测试
    Protocol (网络数据交换规则)
  • 原文地址:https://www.cnblogs.com/ngnetboy/p/5220128.html
Copyright © 2011-2022 走看看