readdir 是一个在 C 语言中用于读取目录内容的函数,它定义在 <dirent.h> 头文件中。在 Ubuntu 系统中,readdir 函数的使用方法和返回值含义与其他 Linux 发行版相同。
readdir 函数的原型如下:
#include <dirent.h>
DIR *opendir(const char *name);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);
readdir 函数接受一个 DIR 类型的指针作为参数,该指针是通过 opendir 函数打开目录后返回的。readdir 函数返回一个指向 struct dirent 结构的指针,该结构包含了目录中的一个条目的信息。如果已经到达目录的末尾,readdir 函数将返回 NULL。
struct dirent 结构的定义如下:
struct dirent {
ino_t d_ino; /* Inode number */
off_t d_off; /* Offset to the next dirent */
unsigned short d_reclen; /* Length of this dirent */
unsigned char d_type; /* Type of file */
char d_name[]; /* Null-terminated filename */
};
struct dirent 结构中的成员含义如下:
d_ino:目录条目的 inode 号。d_off:指向目录中下一个条目的偏移量。d_reclen:当前目录条目的长度(包括文件名)。d_type:文件类型,例如 DT_REG(常规文件)、DT_DIR(目录)、DT_LNK(符号链接)等。d_name:以 null 结尾的文件名。使用 readdir 函数时,通常需要遍历整个目录,直到函数返回 NULL。示例代码如下:
#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");
exit(EXIT_FAILURE);
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
这段代码会打开当前目录(.),然后使用 readdir 函数遍历目录中的所有条目,并打印出每个条目的文件名。最后,使用 closedir 函数关闭目录。