linux命令: tree的c实现

tree命令的c语言实现.

#include<stdio.h>
#include<dirent.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<string.h>
 
#define MAXNAME 200
void s_printf(char *filename,int depth);
void s_dirwalk(char *dirname,int depth,void (*fcn)(char *,int));
void listdirtree(char *dirname,int depth);
 
int main(int argc,char **argv)
{
    if(argc == 1)
        listdirtree(".",0);
    else
    {
        printf("%s\n",argv[1]);
        listdirtree(*++argv,0);
    }
    return 0;
}
 
void listdirtree(char *dirname,int depth)
{
    struct stat stbuf;
    if((stat(dirname,&stbuf)) == -1)
    {
        fprintf(stderr,"listdirtree:can't read file %s information!\n",dirname);
        return;
    }
    if((stbuf.st_mode & S_IFMT) == S_IFDIR)
        s_dirwalk(dirname,depth,listdirtree);
}
 
void s_dirwalk(char *dirname,int depth,void (*fcn)(char *,int))
{
    char name[MAXNAME];
    struct dirent *fip;
    DIR *dp;
    if((dp = opendir(dirname)) == NULL)
    {
        fprintf(stderr,"s_dirwalk:can't open %s\n",dirname);
        return;
    }
    while((fip = readdir(dp)) != NULL)
    {
        if(strcmp(fip->d_name,".") == 0 || strcmp(fip->d_name,"..") == 0)/*skip directory '.' and '..'*/
            continue;
        if(strlen(dirname) + strlen(fip->d_name) + 2 > sizeof(name))
        {
            fprintf(stderr,"s_dirwalk:%s/%s is too long!\n",dirname,fip->d_name);
            return;
        }
        else
        {
            s_printf(fip->d_name,depth);
            sprintf(name,"%s/%s",dirname,fip->d_name);
            (*fcn)(name,depth + 1);
        }
    }
    closedir(dp);
}
 
void s_printf(char *filename,int depth)
{
    while(depth-- > 0)
        printf("|  ");
    printf("|--");
    printf("%s\n",filename);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值