在 Linux 下,opendir
函数本身并不支持递归遍历目录。要实现递归目录遍历,你需要结合 opendir
、readdir
和 closedir
函数,并使用递归函数来处理子目录。以下是一个简单的示例:
#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;
}
if (S_ISDIR(path_stat.st_mode)) {
list_directory_contents(path_stat.path);
} else {
printf("%s\n", path_stat.path);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return EXIT_FAILURE;
}
list_directory_contents(argv[1]);
return EXIT_SUCCESS;
}
这个程序接受一个目录路径作为参数,并递归地列出该目录下的所有文件和子目录。注意,这个程序没有处理符号链接,可能会导致无限递归。要处理符号链接,你需要检查 entry->d_type
是否为 DT_LNK
,并相应地处理。
编译并运行这个程序:
gcc -o list_directory_contents list_directory_contents.c
./list_directory_contents /path/to/directory
将 /path/to/directory
替换为你想要遍历的目录路径。