在Ubuntu中,你可以使用readdir函数来实现递归目录读取。以下是一个简单的示例,展示了如何使用readdir函数递归地读取目录及其子目录中的所有文件和文件夹。
首先,确保你已经安装了必要的头文件:
sudo apt-get install build-essential
然后,创建一个名为recursive_readdir.c的C文件,并添加以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
void read_directory(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
if (!(dir = opendir(path))) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
char path_buf[PATH_MAX];
snprintf(path_buf, sizeof(path_buf), "%s/%s", path, entry->d_name);
if (lstat(path_buf, &statbuf) == -1) {
perror("lstat");
continue;
}
if (S_ISDIR(statbuf.st_mode)) {
read_directory(path_buf);
} else {
printf("%s\n", path_buf);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return EXIT_FAILURE;
}
read_directory(argv[1]);
return EXIT_SUCCESS;
}
保存文件后,使用以下命令编译代码:
gcc -o recursive_readdir recursive_readdir.c
现在,你可以使用以下命令运行程序,递归地读取指定目录及其子目录中的所有文件和文件夹:
./recursive_readdir /path/to/directory
请将/path/to/directory替换为你想要递归读取的目录路径。