简体   繁体   中英

Why readdir returns null and I/O error the next call to readdir after first call on a directory

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

gives this output:

file_name
dir_name
errno = Remote I/O error

in /tmp I have one dir and two files when get to readdir after the execution of opendir(dir) It exits the while and put this error:

errno = Remote I/O error

Why it fails to read the file after the dir in the /tmp directory?

readdir() is not documented to return REREMOTEIO , so most likely sterror() gives misleading information.

Set errno to 0 before entering the while() loop, that is before calling readdir() .

From 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.

To test these two cases when readdir() returns NULL you might like to modify your code like this:

#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");
    }
  }

  ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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