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/