Joefa
Joefa

Reputation: 9

Implementation of ls Command in C

I'm currently taking a system programming course and the prof provide us with a sample code for the ls command implementation

#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
int main (int argc, char *argv[]) {

DIR *dp;
struct dirent *dirp;

if(argc ==1) dp = opendir ("./");

else dp = opendir(argv[1]);

while ((dirp = readdir(dp)) != NULL) printf("%s\n", dirp->d_name);

closedir(dp);
exit(0);
}

However, when I tried to run it, it output the message "segmentation fault". Here is a image of what I did test What is it causing this message?

Upvotes: 0

Views: 5226

Answers (1)

Jabberwocky
Jabberwocky

Reputation: 50831

You invoke your program with ./a.out Assignment1.c.

Then your program does actually a opendir("Assignment1.c");. Because "Assignment1.c" is a file and not a directory, opendir returns NULL.

The you naively do dirp = readdir(dp) with dp being NULL which results in a segmentation fault.

You should test the return value of opendir and display an error message if it is NULL.

Read the opendir man page.

Upvotes: 1

Related Questions