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;
    }
  • 相关阅读:
    Hibernate(十三)迫切内连接fetch
    SQL多表联合查询(交叉连接,内连接,外连接)
    Hibernate入门(十二)离线条件检索
    Java基础IO流(二)字节流小案例
    Java基础IO流(一)
    Hibernate入门(十一)多对多案例
    mysql下载安装及常见问题
    数据库表数据恢复
    linux的自有(内置)服务
    linux下的别名机制
  • 原文地址:https://www.cnblogs.com/wwblog/p/4380535.html
Copyright © 2011-2022 走看看