计算C中嵌套目录中文件的块大小

Calculate blocksize of files in nested directories in C

我一直在尝试递归地计算嵌套文件夹中文件的总块大小。我的代码设法获取第一个文件夹中文件的块大小,但无法读取嵌套在当前文件夹中的文件夹中的文件大小。嵌套文件夹中的文件返回块大小为零。为什么会这样?

int scanDir (char *fstring)
{
    char new_dirname[180] = { 0 };
    int total_size = 0;

    DIR *dir = opendir(fstring);
    if(dir == NULL) {
        perror("Could not open file\n");
        exit(EXIT_FAILURE);
    }

    struct dirent *filenum;
    filenum = readdir(dir);
    while(filenum != NULL) {

        if (strcmp(filenum->d_name, ".") != 0 && strcmp(filenum->d_name, "..") != 0) {

            //Check if file is not a directory
            if (filenum->d_type != DT_DIR ) {

                //Get the size of the file and add it to total size
                struct stat buf;
                int res = lstat(filenum->d_name, &buf);
                if (res == 0){
                    total_size += buf.st_blocks;
                    printf("%s: %ld\n", filenum->d_name, buf.st_blocks);
                }

            }else {
                //If file is a directory
                //Add new path name and the /
                printf("%s\n", filenum->d_name);
                strcat(new_dirname, fstring);
                strcat(new_dirname, "/");
                strcat(new_dirname, filenum->d_name);

                //Add the return value to total size
                total_size += scanDir(new_dirname);
                //Clear the array for the next iteration.
                memset(new_dirname, 0, 180);
            }
        }
        filenum = readdir(dir);
    }
    closedir(dir);
    return (total_size);
}

我解决了!我将一个与文件名相对应的字符串传递给 lstat 而不是文件的相对路径.