在Linux中,opendir()
函数用于打开一个目录流,返回一个指向DIR
结构的指针
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
opendir()
函数打开目录:DIR *dir = opendir(path);
if (dir == NULL) {
// 错误处理
}
当opendir()
函数返回NULL
时,表示打开目录失败。此时,可以使用perror()
函数打印错误信息,或者使用strerror()
函数获取错误描述字符串。
示例1:使用perror()
函数打印错误信息:
if (dir == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
示例2:使用strerror()
函数获取错误描述字符串:
if (dir == NULL) {
fprintf(stderr, "Error opening directory: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
在这两个示例中,如果opendir()
函数失败,程序将打印错误信息并退出。请注意,errno
变量包含了导致错误的系统级错误代码,strerror()
函数将其转换为可读的错误描述字符串。