How to recursively go through folders and count total file size

时光毁灭记忆、已成空白 提交于 2019-12-11 14:49:00

问题


I am trying to recursively go through my directories and print file size, then at the end print the total of all file size's. I cannot figure out what to pass my function recursively, and my variable total does not end up being correct,any help is greatly appreciated, thanks so much in advance.

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>

void do_ls(char[]);
int total = 0;

int main(int ac, char *av[])
{
    if (ac == 1)
        do_ls(".");
    else
    {
        while (--ac) {
            printf("%s:\n", *++av);
            do_ls(*av);
        }
    }
}

void do_ls(char dirname[])
{
    DIR *dir_ptr;
    struct dirent *direntp;
    struct stat info;

    if ((dir_ptr = opendir(dirname)) == NULL)
        fprintf(stderr, "ls01: cannot opern %s\n", dirname);
    else
    {
        while((direntp = readdir(dir_ptr)) != NULL) {
            stat(direntp->d_name, &info);
            if (S_ISDIR(info.st_mode))
                printf("%s\n", direntp->d_name);
                //I believe recursion goes here, I tried the following 
                //do_ls(direntp->d_name);
            else
                printf("%d %s\n", (int)info.st_size, direntp->d_name);
                total += (int)info.st_size;
        }
        closedir(dir_ptr);
    }
    printf("Your total is: %d \n", total);
}

回答1:


In the line:

while((direntp - readdir(dir_ptr)) != NULL)

you should be setting direntp, not subtracting (I assume).



来源:https://stackoverflow.com/questions/50091932/how-to-recursively-go-through-folders-and-count-total-file-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!