readdir 函数是用于读取目录内容的 POSIX 标准函数。在 Debian 或其他基于 Linux 的系统上,你可以使用这个函数来遍历目录中的文件和子目录。下面是一些使用 readdir 函数的基本技巧和示例:

包含头文件:使用 readdir 函数之前,确保包含了必要的头文件:
#include <dirent.h>#include <stdio.h>#include <stdlib.h>打开目录:使用 opendir 函数打开一个目录,并返回一个 DIR 指针。
DIR *dir = opendir(".");if (dir == NULL) {perror("opendir");exit(EXIT_FAILURE);}读取目录项:使用 readdir 函数读取目录中的每一项。
struct dirent *entry;while ((entry = readdir(dir)) != NULL) {printf("%sn", entry->d_name);}关闭目录:使用 closedir 函数关闭目录。
closedir(dir);下面是一个完整的示例程序,演示如何使用 readdir 函数列出当前目录下的所有文件和子目录:
#include <dirent.h>#include <stdio.h>#include <stdlib.h>int main() {DIR *dir;struct dirent *entry;// 打开当前目录dir = opendir(".");if (dir == NULL) {perror("opendir");return EXIT_FAILURE;}// 遍历目录中的每一项while ((entry = readdir(dir)) != NULL) {printf("%sn", entry->d_name);}// 关闭目录closedir(dir);return EXIT_SUCCESS;}过滤特定文件类型:你可以根据需要过滤特定类型的文件。例如,只列出 .txt 文件:
while ((entry = readdir(dir)) != NULL) {if (strstr(entry->d_name, ".txt") != NULL) {printf("%sn", entry->d_name);}}获取文件的详细信息:结合 stat 函数可以获取文件的详细信息,如文件大小、修改时间等。
struct stat file_stat;char path[1024];while ((entry = readdir(dir)) != NULL) {snprintf(path, sizeof(path), "./%s", entry->d_name);if (stat(path, &file_stat) == 0) {printf("%s - %ld bytesn", entry->d_name, file_stat.st_size);}}递归遍历目录:如果你需要递归遍历目录及其子目录,可以编写一个递归函数。
void list_directory(const char *path) {DIR *dir;struct dirent *entry;char full_path[1024];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;}snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);if (entry->d_type == DT_DIR) {list_directory(full_path);} else {printf("%sn", full_path);}}closedir(dir);}int main() {list_directory(".");return EXIT_SUCCESS;}通过这些技巧和示例,你应该能够在 Debian 系统上有效地使用 readdir 函数来处理目录和文件。