代码改变世界

递归打印当前目录下的所有文件的文件名和文件大小

2015-03-31 12:37  微尘_无名  阅读(592)  评论(0编辑  收藏  举报

递归打印当前目录下的所有文件的文件名和文件大小,在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\n", 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\n", 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\n", name);
        return;
    }

    if((st_buf.st_mode & S_IFMT) == S_IFDIR)
    {
        printf("%ld %s\n", st_buf.st_size, name);
        dirwalk(name, fsize);
        printf("\n\n");
    }else
    {
        printf("%ld %s\n", st_buf.st_size, name);
    }
}

int main(int argc, char* argv[])
{
    if(argc == 1)
        fsize(".");
    while(--argc)
        fsize(*++argv);
    return 0;
}