zoukankan      html  css  js  c++  java
  • 递归打印当前目录下的所有文件的文件名和文件大小

    递归打印当前目录下的所有文件的文件名和文件大小,在ubuntu14.04下编译通过:

    /*************************************************************************
        > File Name: dirwalk.c
        > Author: 
        > Mail: 
        > Created Time: Tue 31 Mar 2015 11:56:38 AM CST
     ************************************************************************/
    
    #include<stdio.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <string.h>
    #include <dirent.h>
    
    #define MAX_PATH 1024
    
    
    
    /*dirwalk: apply fcn to all files in dir */
    void dirwalk(char* dir, void(*fcn)(char*))
    {
        struct dirent *dp;
        DIR* dfd;
    
        char name[MAX_PATH];
        if((dfd = opendir(dir)) == NULL)
        {
            fprintf(stderr, "dirwalk: can't open %s
    ", dir);
            return;
        }
    
        while((dp = readdir(dfd)) != NULL)
        {
            if(strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0)
            {
                continue;
            }
    
            if(strlen(dir) + strlen(dp->d_name) + 2 > sizeof(name))
            {
                fprintf(stderr, "%s/%s too long
    ", dir, dp->d_name);
            }else
            {
                sprintf(name, "%s/%s", dir, dp->d_name);
                (*fcn)(name);
            }
        }
        closedir(dfd);
    }
    
    /* print the file name and the size of the "name" */
    
    void fsize(char* name)
    {
        struct stat st_buf;
        if(stat(name, &st_buf) < 0)
        {
            fprintf(stderr, "fsize: can't access %s
    ", name);
            return;
        }
    
        if((st_buf.st_mode & S_IFMT) == S_IFDIR)
        {
            printf("%ld %s
    ", st_buf.st_size, name);
            dirwalk(name, fsize);
            printf("
    
    ");
        }else
        {
            printf("%ld %s
    ", st_buf.st_size, name);
        }
    }
    
    int main(int argc, char* argv[])
    {
        if(argc == 1)
            fsize(".");
        while(--argc)
            fsize(*++argv);
        return 0;
    }
  • 相关阅读:
    谈谈关于个人提升的一些思考
    asp.net 委托用法
    DNN 配置 数据库篇
    一个技术为主的博客沦落为娱乐休息的场所
    NDO 组件和例子下载,内置了一个基于Velocity模版引擎的代码生成器
    DNN 研究路线图
    学习DNN开发模块插件的几条主线
    NDO 快速入门
    NDO 简介
    也谈代码生成器
  • 原文地址:https://www.cnblogs.com/wwblog/p/4380535.html
Copyright © 2011-2022 走看看