在Linux中,当使用opendir()函数打开一个目录时,如果操作失败,该函数会返回NULL
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir("/path/to/directory");
if (dir == NULL) {
// opendir() failed
fprintf(stderr, "Error opening directory: %s\n", strerror(errno));
return 1;
}
// Successfully opened the directory, process entries here
closedir(dir);
return 0;
}
在这个示例中,我们首先尝试使用opendir()函数打开一个目录。如果opendir()返回NULL,我们使用strerror()函数和全局变量errno来获取错误信息,并将其打印到标准错误输出。如果opendir()成功,我们可以继续处理目录中的条目。最后,我们使用closedir()函数关闭目录。