Question: Objective In this assignment, you will be writing a program that opens a directory, parses each directory entry, displays the file size and name, and
Objective
In this assignment, you will be writing a program that opens a directory, parses each directory entry, displays the file size and name, and recursively open subdirectories. With no argument provided, your program will open the current working directory. If an argument is provided, your program will open the directory specified. In order to create this program, you need to use the following programming APIs:
DIR *opendir(const char *name); struct dirent *readdir(DIR *dirp); int lstat(const char *path, struct stat *buf);
Your program will keep a total of bytes used by each file and display that total at the end of your program run. Do not display totals for each directory, just the end of your main function.
Output
Your output should be formatted like this:
$ ./p7 dir .
17371:assn8
170:Makefile
1715:assn8.c
11416:assn8.o
Total file space used:30672
If you run this on the server with /usr/share/man as an argument, it should look like this:
$ ./p7 /usr/share/man
dir /usr/share/man
dir /usr/share/man/fr.ISO8859-1
dir /usr/share/man/fr.ISO8859-1/man8
1268:iwpriv.8.gz
1568:iwlist.8.gz
1200:iwgetid.8.gz
1319:iwspy.8.gz
1405:iwevent.8.gz
7946:iwconfig.8.gz
dir /usr/share/man/fr.ISO8859-1/man7
1473:wireless.7.gz
dir /usr/share/man/fr
dir /usr/share/man/fr/man8
901:installkernel.8.gz
... many lines of data ...
1851:newgrp.1.gz
dir /usr/share/man/vi
dir /usr/share/man/vi/man1
6335:podebconf-report-po.1.gz
2588:podebconf-display-po.1.gz
2470:debconf-updatepo.1.gz
3129:po2debconf.1.gz
3306:debconf-gettextize.1.gz
dir /usr/share/man/vi/man7
9071:po-debconf.7.gz
Total file space used:21432927
Keep in mind that this example will change when the server is updated.
Notes
The primary problem people have with this assignment is recursion. If you create a function that takes a string parameter that contains the directory to list, then you should be able to use recursion to list subdirectories.
When you are looping through each directory entry, you will want to detect if the file is a regular file or a directory. Ignore everything else, including symbolic links. This is why you want to use the lstat API (note the letter 'L' at the start of the function name).
You can check the type of the directory entry by using the S_ISDIR, S_ISREG and/or S_ISLNK macros as shown in the stat man page.
The second major problem students have with this assignment is building the path from the directory entry and filename. There is a really nifty function call asprintf. Look it up, it helps.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
