readdir
函数是 Linux 系统中用于读取目录内容的函数,它定义在 <dirent.h>
头文件中。readdir
函数用于遍历目录中的每个条目(文件或子目录)。
#include <dirent.h>
struct dirent *readdir(DIR *dirp);
DIR *dirp
: 指向一个已打开的目录流的指针。通常通过 opendir
函数打开一个目录并返回一个 DIR
指针。struct dirent
结构的指针,该结构包含目录条目的信息。NULL
。struct dirent
结构struct dirent
结构通常包含以下字段:
ino_t d_ino
: 目录条目的 inode 号。off_t d_off
: 条目在目录文件中的偏移量。unsigned short d_reclen
: 条目的长度。char d_type
: 条目的类型(例如,DT_REG 表示常规文件,DT_DIR 表示目录)。char d_name[]
: 条目的名称。下面是一个简单的示例,演示如何使用 readdir
函数遍历当前目录中的所有文件和子目录:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
int main() {
DIR *dir;
struct dirent *entry;
// 打开当前目录
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
// 遍历目录中的每个条目
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
// 关闭目录
closedir(dir);
return EXIT_SUCCESS;
}
readdir
时,应该检查返回值是否为 NULL
,以确定是否到达目录末尾或发生了错误。readdir
返回的 struct dirent
结构是由内核分配的,不需要手动释放内存。readdir
不是线程安全的函数。如果在多线程环境中使用,需要适当的同步机制。通过这些基本的使用方法和注意事项,你可以有效地使用 readdir
函数来读取和处理目录内容。