简体   繁体   English

列出Ubuntu中目录中的文件

[英]Listing files in Directory in Ubuntu

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;
}
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. 您当前的表达式被解析为dirpent = (readdir(dirp) != NULL) ,它将dirpent设置为0或1。

If you indent your program with indent rd.c then compile your program with gcc -Wall -g rd.c -o rd you get 如果使用indent rd.c缩进程序,然后使用gcc -Wall -g rd.c -o rd编译程序,则会得到

 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应该是

 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 . 使用gdb调试器(及其bt命令)来找出导致SIGSEGV导致程序崩溃的原因。

Don't forget to carefully read documentation like readdir(3) man page and Advanced Linux Programming book. 不要忘了仔细阅读readdir(3)手册页和Advanced Linux Programming书之类的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM