Search code examples
cdirectory-structurefilesizestatopendir

Calculate blocksize of files in nested directories in C


I have been trying to calculate total block size of files recursively in nested folders. My code manages to get the block size of the files in the first folder but fails to read the size of files in folders nested in the current folder. The files in nested folders are returning block size of zero. Why is tha so?

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);
}

Solution

  • I solved it! I was passing a string corresponding to the name of the file to lstat and not the relative path to the fileSynopsis för the stat function.