码迷,mamicode.com
首页 > 系统相关 > 详细

linux嵌入式: 实现自己的tree命令

时间:2016-03-29 19:25:24      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

 

//# cat treecmd.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);
}

//使用交叉编译工具链编出来后,拷贝到系统目录下

 

linux嵌入式: 实现自己的tree命令

标签:

原文地址:http://www.cnblogs.com/mylinux/p/5334024.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!