I am trying to list files in the parent directory of the current directory, but when I try to execute this program from terminal I get Segmentation Error.. What am I doing wrong? Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
int main(int argc, char *argv[])
{
struct dirent *dirpent;
DIR *dirp;
if(argc!=2)
{
printf("Cant continue with the program\n");
return 0;
}
dirp= opendir(argv[1]);
if(dirp)
{
while(dirpent=readdir(dirp) !=NULL)
printf("%s\n",dirpent->d_name);
closedir(dirp);
}
return 0;
}
should be
Your current expression is parsed as
dirpent = (readdir(dirp) != NULL)
, which will setdirpent
to either 0 or 1.If you indent your program with
indent rd.c
then compile your program withgcc -Wall -g rd.c -o rd
you getSo you forgot parenthesis, your
while
should bePlease compile your program with all warnings (and improve it till they are all gone) before asking questions. Use the
gdb
debugger (and itsbt
command) to find out why a program crash withSIGSEGV
.Don't forget to carefully read documentation like readdir(3) man page and Advanced Linux Programming book.