在Linux中,readdir函数用于读取目录中的条目。要实现目录结构的遍历,你可以使用递归方法来遍历所有子目录。以下是一个简单的示例,展示了如何使用readdir和opendir函数来实现目录结构遍历:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
void list_directory_contents(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat path_stat;
dir = opendir(path);
if (!dir) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
snprintf(path_stat.path, sizeof(path_stat.path), "%s/%s", path, entry->d_name);
if (stat(path_stat.path, &path_stat) == -1) {
perror("stat");
continue;
}
printf("%s\n", path_stat.path);
if (S_ISDIR(path_stat.st_mode)) {
list_directory_contents(path_stat.path);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory_path>\n", argv[0]);
return EXIT_FAILURE;
}
list_directory_contents(argv[1]);
return EXIT_SUCCESS;
}
这个程序接受一个命令行参数,即要遍历的目录路径。它首先打开目录,然后使用readdir函数读取目录中的每个条目。对于每个条目,它使用stat函数获取文件或目录的信息。如果条目是一个目录,程序会递归地调用list_directory_contents函数来遍历子目录。
编译并运行此程序,传入要遍历的目录路径作为参数,你将看到该目录及其所有子目录的结构。