[英]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 我目前正在参加系统编程课程,教授为我们提供了ls命令实现的示例代码
#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". 但是,当我尝试运行它时,它会输出消息“ segmentation fault”。 Here is a image of what I did test What is it causing this message?
这是我测试过的图片,它是什么导致此消息的?
You invoke your program with ./a.out Assignment1.c
. 您使用
./a.out Assignment1.c
调用程序。
Then your program does actually a opendir("Assignment1.c");
然后,您的程序实际上执行了一个
opendir("Assignment1.c");
. 。 Because
"Assignment1.c"
is a file and not a directory, opendir
returns NULL
. 因为
"Assignment1.c"
是文件而不是目录,所以opendir
返回NULL
。
The you naively do dirp = readdir(dp)
with dp
being NULL
which results in a segmentation fault. 您天真地执行
dirp = readdir(dp)
,而dp
为NULL
,这会导致分段错误。
You should test the return value of opendir
and display an error message if it is NULL
. 您应该测试
opendir
的返回值,如果它为NULL
,则显示一条错误消息。
Read the opendir man page . 阅读opendir手册页 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.