zoukankan      html  css  js  c++  java
  • apue编程之参考du代码利用递归写的一个简单的du命令的源代码

    #include <stdio.h>
    #include <stdlib.h>
    #include <glob.h>
    #include <string.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <unistd.h>
     
    #define PATHSIZE 1024
     
    static int path_noloop(const char *path)
    {
        char *pos;
     
        pos = strrchr(path,'/');//定位最右边的'/'的位置
     
        if(strcmp(pos+1,".") == 0 || (strcmp(pos+1,"..") == 0))
            return 0;
        return 1;
     
    }
     
    static int64_t mydu(const char *path)
    {
        int i;
        glob_t globres;
        int64_t sum;
        static struct stat statres;
        static char nextpath[PATHSIZE];
     
        if(lstat(path, &statres) < 0)
        {
            perror("lstat()");
            return 0;//exit(1);
        }
         
        if(!S_ISDIR(statres.st_mode))
            return statres.st_blocks;
     
        strncpy(nextpath, path,PATHSIZE);
        strncat(nextpath, "/*" , PATHSIZE);
        glob(nextpath,GLOB_NOSORT, NULL, &globres);
         
        strncpy(nextpath, path,PATHSIZE);
        strncat(nextpath, "/.*" , PATHSIZE);
        glob(nextpath,GLOB_NOSORT|GLOB_APPEND, NULL, &globres);
         
        sum = statres.st_blocks;
     
        for(i = 0 ;i < globres.gl_pathc ; i++)
        {
            if(path_noloop(globres.gl_pathv[i]))
                sum += mydu(globres.gl_pathv[i]);
        }
         
     
        return sum;
    }
     
    int main(int argc,char **argv)
    {
        if(argc < 2)
        {
            fprintf(stderr,"Usage...
    ");
            exit(1);
        }
             
        printf("%lld 512B blocks
    ",mydu(argv[1]));
     
        return 0;
    }
  • 相关阅读:
    【C++注意事项】1 数据类型及类型转换
    【万里征程——Windows App开发】动态磁贴
    背包问题
    Fence Repair
    Saruman's Army
    字典序最小问题——Best Cow Line
    区间调度问题
    硬币问题
    数据库查询优化的一些总结
    关于减少BUG的思考
  • 原文地址:https://www.cnblogs.com/dbtech/p/5552277.html
Copyright © 2011-2022 走看看