在Ubuntu中,你可以使用readdir函数来实现递归读取目录。以下是一个简单的示例,展示了如何使用C语言和dirent.h库中的readdir函数来递归地读取目录及其子目录中的所有文件和文件夹。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
void list_directory_contents(const char *path) {
struct dirent *dp;
DIR *dir = opendir(path);
if (!dir) {
perror("opendir");
return;
}
while ((dp = readdir(dir)) != NULL) {
if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0) {
continue;
}
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", path, dp->d_name);
struct stat st;
if (stat(full_path, &st) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(st.st_mode)) {
printf("Directory: %s\n", full_path);
list_directory_contents(full_path);
} else {
printf("File: %s\n", full_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;
}
要编译并运行此程序,请将其保存为list_directory_contents.c,然后在终端中执行以下命令:
gcc -o list_directory_contents list_directory_contents.c
./list_directory_contents /path/to/directory
这将递归地列出指定目录及其所有子目录中的文件和文件夹。