Question: List Files: Write a C program that lists files in the given directory. When called without any arguments, the program should just print the file

List Files: Write a C program that lists files in the given directory. When called without any arguments, the program should just print the file names. When invoked with the -l flag, the program should print out information about each file, such as the owner, group, permissions, and other information obtained from the stat() system call. The program should take one additional argument, which is the directory to read, e.g., myls -l directory. If no directory is given, the program should just use the current working directory. Useful interfaces: stat(), opendir(), readdir(), getcwd().

Your code should take a directory name argument on the command line, or if no command-line argument is provided, it should use the current working directory. Here is an example of how your code should work:

$ ls

Makefile myls myls.c tempdir

$ ./myls

tempdir

.

Makefile

..

myls

myls.c

$ ls tempdir

baz.txt

$ ./myls tempdir

.

..

baz.txt

$ ls .

Makefile myls myls.c tempdir

$ ./myls .

tempdir

.

Makefile

..

myls

myls.c

$

The files can be listed in any order, and it will be easiest if you output . and ... For extra credit, also implement the -l flag. When this flag is used, your code should output owner permissions, inode, and name of each file, like this:

$ ./myls -l

rwx 1844983 tempdir

rwx 1844964 .

rw 1844980 Makefile

rwx 1065059 ..

rwx 1844977 myls

rw 1844986 myls.c

$ ./myls -l tempdir

rwx 1844983 .

rwx 1844964 ..

rw 1844985 baz.txt

$ ./myls -l .

rwx 1844983 tempdir

rwx 1844964 .

rw 1844980 Makefile

rwx 1065059 ..

rwx 1844977 myls

rw 1844986 myls.c

$

Note the suggestions in the OSTEP question about which system calls to use (such as getcwd). Your code should run correctly on the hosting machine.

Hint: you only need stat() if you support the -l option.

You code should be named myls.c and should be compiled like this:

$ gcc -o myls myls.c

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!