How to find out the size of the files from a directory

692 views Asked by At

So I have this piece of code that shows all the files of a directory on my raspberry PI by launchint it like: "./Readdir /etc". I need to modifiy it so that it also prints the size of the files. I tried adding another print statement that prints the size of a struct like this: printf(sb.st_size), sb being declared as struct stat sb, but this only prints the size of the directory itself. Anyone know how to help me? Thanks in advance!

/*  Readdir.c - Read the current working directory */

#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char * argv[]) {
    if(argc>=2) {
        DIR *dirp = opendir(argv[1]) ;
        if ( dirp != NULL ) {
            struct dirent *dp ;
            while ((dp = readdir(dirp))) {
                char t;
                switch( dp->d_type ) {
                    case DT_BLK     : t = 'b' ; break ;
                    case DT_CHR     : t = 'c' ; break ;
                    case DT_DIR     : t = 'd' ; break ;
                    case DT_FIFO    : t = 'p' ; break ;
                    case DT_LNK     : t = 'l' ; break ;
                    case DT_REG     : t = '-' ; break ;
                    case DT_SOCK    : t = 's' ; break ;
                    case DT_UNKNOWN : t = 'u' ; break ;
                    default         : t = '?' ;
                }
                printf("%8d %c %s\n", (int)dp->d_ino, t, dp->d_name);
            }
            closedir(dirp);
        }
        return 0;
    } else {
        printf("usage: %s dir\n", argv[0]);
        return 1;
    }
}
1

There are 1 answers

2
user3629249 On

when the dp->d_type field is: DT_REG

Then

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

struct stat  fileStat;
if( ! stat( dp->d_name, &fileStat ) )
{
    printf( "%d\n", fileStat.st_size );
}