在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替換為你想要遞歸讀取的目錄路徑。