CS 246 Lab 11

Write a program called filetree that lists the files in a directory and recursively traverses through all subdirectories. It will take a starting directory as a single command line argument.

The output will look like this (this is output from running filetree on /home/mathcs/courses/cs246/tree):

/home/mathcs/courses/cs246/tree
|- epsilon
    |- three
        |- a
            |- 1
    |- four
    |- two
    |- one
|- delta
|- alpha
    |- three
    |- four
    |- two
    |- one
|- gamma
|- beta

You need to write a function that processes one directory, passing the directory name as an argument. You will also pass an integer argument that is the recursion depth. This argument will tell you how much to indent at the beginning of each line. When you do the recursive call, just increment the depth. The indentation should be 4 spaces for each recursion level.

Your function that processes a directory will look much like the readdir program that we did in class. However, for each file, you must use the stat system call to determine if it is a directory. If so, do a recursive call.

When you do the recursive call, you need to pass an extended path name. If you are currently processing a directory a/b/c and you want to do a recursive call with a subdirectory d, you will have to construct the string a/b/c/d. You can copy a/b/c with strcpy and add on /d with strcat. However, you MUST allocate space for the longer name with malloc. You can use strlen to determine how much space you need. Be sure to include the null character at the end of the string. After the recursive call is done, you should free newly allocated string. Also, when you are through processing a directory, use closedir to close the directory stream.

Every directory will contain the entries . and ... Leave these out of your list and do not call your listing function recursively on them (doing so will give an infinite recursion).

Make sure you check for command line arguments.