readdir() 是一个在 C 语言中用于读取目录内容的函数,它的原型定义在 <dirent.h> 头文件中。readdir() 函数用于遍历目录中的文件和子目录。它的返回值是一个指向 struct dirent 结构的指针,该结构包含了关于目录项的信息。
readdir() 返回值解析当调用 readdir() 函数时,如果成功,它将返回一个指向 struct dirent 结构的指针,该结构包含以下字段:
d_ino: 目录项的 inode 号。d_off: 目录项在目录文件中的偏移量。d_reclen: 目录项的长度。d_name: 目录项的名称。如果到达目录的末尾,readdir() 将返回 NULL。
readdir() 函数通常用于以下场景:
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");
exit(EXIT_FAILURE);
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
.txt 文件。// ...(省略部分代码)
while ((entry = readdir(dir)) != NULL) {
if (strstr(entry->d_name, ".txt") != NULL) {
printf("%s\n", entry->d_name);
}
}
// ...(省略部分代码)
readdir() 函数,可以遍历多层目录结构。// ...(省略部分代码)
void list_directory_contents(const char *path) {
DIR *dir;
struct dirent *entry;
dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
if (entry->d_type == DT_DIR) {
list_directory_contents(full_path);
} else {
printf("%s\n", full_path);
}
}
closedir(dir);
}
// ...(省略部分代码)
int main() {
list_directory_contents(".");
return 0;
}
总之,readdir() 函数在处理目录和文件操作时非常有用,可以帮助我们实现各种文件管理任务。