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

递归打印当前目录下的所有文件的文件名和文件大小,在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;
}
原文地址:https://www.cnblogs.com/wwblog/p/4380535.html