在Ubuntu中,readdir函数本身并不支持递归读取目录。readdir函数用于读取一个目录流中的条目,但它只会返回当前目录下的文件和子目录,而不会递归地进入子目录。
如果你需要递归地读取目录,你可以编写一个递归函数来实现这个功能。以下是一个简单的示例:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void read_directory_recursive(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;
}
char full_path[1024];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
if (stat(full_path, &path_stat) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(path_stat.st_mode)) {
read_directory_recursive(full_path);
} else {
printf("%s\n", full_path);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return 1;
}
read_directory_recursive(argv[1]);
return 0;
}
这个程序接受一个目录路径作为参数,并递归地读取该目录及其所有子目录中的文件。请注意,这个示例程序没有处理符号链接和其他可能的错误情况。在实际应用中,你可能需要根据具体需求进行相应的调整。