c - 为什么 readdir 在第一次调用目录后下次调用 readdir 时返回 null 和 I/O 错误

标签 c linux readdir

DIR *dir_ptr;
struct dirent *dir_entery;
dir_ptr = opendir("/tmp");

while (dir_ptr&&(dir_entery = readdir(dir_ptr))) {
   printf("%s \n", dir_entery->d_name);
}

printf("%s \n", strerror(errno));

给出这个输出:

file_name
dir_name
errno = Remote I/O error

/tmp中,在执行opendir(dir)后到达readdir时,我有一个目录和两个文件,它退出了同时并发出此错误:

errno = Remote I/O error

为什么/tmp目录下的dir后面的文件读取失败?

最佳答案

readdir() 没有记录返回 REREMOTEIO,因此很可能 sterror() 提供了误导性信息。

在进入while()循环before之前将errno设置为0,即before 调用 readdir()

来自man readdir :

If the end of the directory stream is reached, NULL is returned and errno is not changed. If an error occurs, NULL is returned and errno is set appropriately. To distinguish end of stream and from an error, set errno to zero before calling readdir() and then check the value of errno if NULL is returned.

要在 readdir() 返回 NULL 时测试这两种情况,您可能需要像这样修改代码:

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>

  ...

  DIR * dir_ptr = opendir("/tmp");
  if (NULL != dir_ptr)
  {
    perror("opendir() failed");
  }
  else
  {
    struct dirent * dir_entery;

    errno = 0; 
    while ((dir_entery = readdir(dir_ptr))) /* an extra pair of parenthesis here to silence GCC */
    {
      printf("%s\n", dir_entery->d_name);
    }

    if (0 != errno)
    {
      perror("readdir() failed");
    }
    else
    {
      printf("No more entries.\n");
    }
  }

  ...

关于c - 为什么 readdir 在第一次调用目录后下次调用 readdir 时返回 null 和 I/O 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16841590/

相关文章:

c - 使用结构指针作为参数对函数进行原型(prototype)设计

python - centos 7 上的 Python 3.6 中缺少 turtle 图形模块?

linux - 从 bash 脚本启动时 Logstash 关闭停止

c - 类型 "long long"总是 64 位吗?

c - free() 函数只释放结构的第一个元素?

c - 如何在 Linux 中获取文件创建日期?

c++ - CMake - target_link_libraries 和真实的库名称

Node.js fs.readdir 递归目录搜索

检查一个目录。 readdir 返回的条目是目录、链接或文件。 dent->d_type 没有显示类型

php 文件名编码,ö 不是真正的 ö 或者 "o ̈ "是什么?