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;
    }
  • 相关阅读:
    java面试第八天
    java面试第七天
    java面试第六天
    java面试第五天
    java面试第四天
    SpringMVC导出Excel
    75. Autorelease机制及释放时机
    关于 SQLNET.AUTHENTICATION_SERVICES 验证方式的说明
    硬件十万个为什么——运放篇(五)PCB设计技巧
    eclipse到Android Studio的项目迁移
  • 原文地址:https://www.cnblogs.com/wwblog/p/4380535.html
Copyright © 2011-2022 走看看