how to get the size of a dir programatically in linux?

c, dir, linux, size

Solution

Based on Jim Plank's example to get you started:

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

int main( int argc, char **argv ) {
  DIR *d = opendir( "." );

  if( d == NULL ) {
    fprintf( stderr, "Cannot open current working directory\n" );
    return 1;
  }

  struct dirent *de;
  struct stat buf;
  int total_size = 0;

  for( de = readdir( d ); de != NULL; de = readdir( d ) ) {
    int exists = stat( de->d_name, &buf );

    if( exists < 0 ) {
      fprintf( stderr, "Cannot read file statistics for %s\n", de->d_name );
    } else {
      total_size += buf.st_size;
    }
  }

  closedir( d );
  printf( "%d\n", total_size );

  return 0;
}

Notes, considerations, and questions for the reader:

- This is example is incomplete. See Plank's notes for more details.

- What happens if there are locked files?

- Do symbolic links need special handling (to avoid infinite loops)?

- How would you output the full path name for erroneous files?

This answer is a starting point, not a complete and robust program to calculate directory sizes. If you need more help, read the source code for the `du` program.

Problem

I want to get the exact size of a particular dir in linux through a C program. I tried using statfs(path,struct statfs &) but it doesn't give exact size. I also tried with stat() but it returns size as 4096 for any dir ! Please suggest me the way through which I can get the exact size of dir just like we get after "du -sh dirPath" command. Also I dont wanna use du through system(). Thanks in advance.

Original source