简体   繁体   English

带readdir的Segfault()

[英]Segfault with readdir()

I'm just starting with C programming, and i'm trying to read and display files in a directory (just like the ls command). 我刚开始使用C编程,我正在尝试读取和显示目录中的文件(就像ls命令一样)。

Here's a part of my code where I get a segfault, and I have no clue why: 这是我的代码的一部分,我得到一个段错误,我不知道为什么:

void    display_dir(char *dir)
{
  DIR   *strm;
  struct dirent *direct;

  if((strm = opendir(dir) == NULL))
    {
      printf("ERROR: Couldn't open directory.\n");
      exit(1);
    }
while ((direct = readdir(strm)) != NULL)
    display_elems(direct);
  closedir(strm);
}

After some tests, it appears that the program segfault when it reaches: 经过一些测试后,看来程序会在达到时遇到段错误:

while ((direct = readdir(strm)) != NULL)

I've done some researches, but I didn't find anything that could help me. 我做了一些研究,但我找不到任何可以帮助我的东西。

if((strm = opendir(dir) == NULL))

The parentheses are nested wrong. 括号嵌套错误。 It should be: 它应该是:

if((strm = opendir(dir)) == NULL)

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

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