opendir() 和 readdir() 是在 Linux 系统中用于读取目录内容的两个函数,它们之间的关系是协同工作的。
opendir() 函数。如果成功,它会返回一个非空的 DIR 指针;如果失败,则返回 NULL。函数原型:
#include <dirent.h>
DIR *opendir(const char *name);
readdir() 函数,它都会返回一个指向 dirent 结构的指针,该结构包含了目录项的信息(如文件名、文件类型等)。当没有更多的目录项可读时,readdir() 函数将返回 NULL。函数原型:
#include <dirent.h>
struct dirent *readdir(DIR *dirp);
使用这两个函数的典型步骤如下:
opendir() 函数打开目录,获取一个 DIR 指针。readdir() 函数,读取目录中的每个条目。readdir() 返回 NULL 时,表示已到达目录末尾,关闭目录流。closedir() 函数关闭目录流。示例代码:
#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
这个示例程序会列出当前目录下的所有文件和子目录。