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


    //# 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
    ",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!
    ",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
    ",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!
    ",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
    ",filename);
    }
    
    //使用交叉编译工具链编出来后,拷贝到系统目录下
  • 相关阅读:
    vue : 无法加载文件 C:UsersXXXAppDataRoaming pmvue.ps1,因为在此系统上禁止运行脚本
    js全屏和退出全屏浏览器
    js 如何保存代码段并执行以及动态加载script
    计算年龄,精确到年月日
    js闭包问题
    构造函数和继承方法
    js 箭头函数不适用的场景
    获取一组数据的最大值和最小值
    地图
    json传输
  • 原文地址:https://www.cnblogs.com/mylinux/p/5334024.html
Copyright © 2020-2023  润新知