tags:

views:

319

answers:

2

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.

+4  A: 

You need to stat() all the files in the current directory and sub directories and add them up.

Consider using a recursive algorithm for this.

Byron Whitlock
+2  A: 

Typical Solution

If you want the size of a directory, similar in fashion to du, create a recursive function. It is possible to solve the problem iteratively, but the solution lends itself to recursion.

Information

Here is a link to get you started:

http://www.cs.utk.edu/~plank/plank/classes/cs360/360/notes/Prsize/lecture.html

Search

Here is a link showing you how I discovered that web page:

http://tinyurl.com/mskxle

Example

Directly from Jim Plank's website, serving as an example to get you started.

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

main()
{
  DIR *d;
  struct dirent *de;
  struct stat buf;
  int exists;
  int total_size;

  d = opendir(".");
  if (d == NULL) {
    perror("prsize");
    exit(1);
  }

  total_size = 0;

  for (de = readdir(d); de != NULL; de = readdir(d)) {
    exists = stat(de->d_name, &buf);
    if (exists < 0) {
      fprintf(stderr, "Couldn't stat %s\n", de->d_name);
    } else {
      total_size += buf.st_size;
    }
  }
  closedir(d);
  printf("%d\n", total_size);
}
Dave Jarvis
You don't have to do it recursively, you can do directory traversal iteratively as well ;)
Byron Whitlock
True. Although recursion is likely the most common solution. Fixed.
Dave Jarvis