Counting Directory Size Recursively Using C

I’ve just found this great articles at Jim Plank website. I know, it was lots easier using linux du command

Without any further nonsense talk, here we go. First we need download some source code at Jim Plank website

# mkdir prsize
# cd prsize
# wget http://www.cs.utk.edu/~plank/plank/classes/cs360/360/notes/Prsize/prsize8.c
# wget http://www.cs.utk.edu/~plank/plank/classes/cs360/360/src/dllist.c
# wget http://www.cs.utk.edu/~plank/plank/classes/cs360/360/notes/Dllists/dllist.h
# wget http://www.cs.utk.edu/~plank/plank/classes/cs360/360/src/jrb.c
# wget http://www.cs.utk.edu/~plank/plank/classes/cs360/360/include/jrb.h
# wget http://www.cs.utk.edu/~plank/plank/classes/cs360/360/src/jval.c
# wget http://www.cs.utk.edu/~plank/plank/classes/cs360/360/include/jval.h

prsize8.c is the main program, while dllist.c/h jrb.c/h jval.c/h is library that prsize8 statically linked in.

Now we need to create some static library.(Original website doesn’t explain how to create the libs)

# gcc -c dllist.c -o dllist.o
# gcc -c jrb.c -o jrb.o
# gcc -c jval.c -o jval.o

# ar rcs libdllist.a dllist.o
# ar rcs libjrb.a jrb.o
# ar rcs libjval.a jval.o

Compile time 🙂

But, before that fun part, i modified the main function a bit

main(int argc,char **argv)
{
  JRB inodes;

  inodes = make_jrb();

  if(argc<2)
  {     
        printf("Usage: %s dir\n", argv[0]);
        exit(0);
  }
  
  printf("%d\n", get_size(argv[1], inodes));
}

Now compile

# gcc -static prsize8.c -L. -ljrb -ldllist -ljval -o prsize8

Test the program

# ./prsize8 /tmp
23018905
# du -sb /tmp
23014809        /tmp

enjoy 🙂

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *