Listing files in Directory in Ubuntu

十年热恋 提交于 2019-12-12 03:57:48

问题


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;
}

回答1:


dirpent=readdir(dirp) !=NULL

should be

(dirpent = readdir(dirp)) != NULL

Your current expression is parsed as dirpent = (readdir(dirp) != NULL), which will set dirpent to either 0 or 1.




回答2:


If you indent your program with indent rd.c then compile your program with gcc -Wall -g rd.c -o rd you get

 rd.c: In function 'main':
 rd.c:21:22: warning: assignment makes pointer from integer without a cast [enabled by default]
 rd.c:21:7: warning: suggest parentheses around assignment used as truth value [-Wparentheses]

So you forgot parenthesis, your while should be

 while((dirpent=readdir(dirp)) !=NULL)

Please compile your program with all warnings (and improve it till they are all gone) before asking questions. Use the gdb debugger (and its bt command) to find out why a program crash with SIGSEGV.

Don't forget to carefully read documentation like readdir(3) man page and Advanced Linux Programming book.



来源:https://stackoverflow.com/questions/12989228/listing-files-in-directory-in-ubuntu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!