B09 Lab week 8

This lab is on learning and practicing opendir, readdir, and closedir to read a directory. They are fairly straightforward; please read their man pages (e.g., “man readdir”) for how to use them.

Write a C program list.c that takes 1 to 2 command-line arguments. Treat the 1st argument as the pathname of a directory. Using opendir, readdir, and closedir, read the filenames in that directory and print them to stdout, one per line.

You will notice that the filenames are not sorted. This is normal. Just print in the order you find. (“ls -1f” gives the same order, you can use it to check.)

If the 2nd argument exists, it will be a single character. (If you see more characters, ignore them.) In this case, do not print filenames that start with that character.

For simplicity, you may assume legal inputs as promised above, and omit most error handling, though it is always a good idea to check whether opendir actually succeeds. If you add debugging/error messages for your sake, please send them to stderr only.

Example: If a certain directory has:

$ ls -1f dir
testsuite.csv
..
.
pose
sample-main.c
marking-scheme.yml

Then running your program for it gives:

$ ./a.out dir
testsuite.csv
..
.
pose
sample-main.c
marking-scheme.yml

And with the 2nd parameter:

$ ./a.out dir .
testsuite.csv
pose
sample-main.c
marking-scheme.yml

or this:

$ ./a.out dir p
testsuite.csv
..
.
sample-main.c
marking-scheme.yml

Please submit your C file as list.c