在Ubuntu中,使用readdir
函數可以遍歷目錄并處理子目錄。readdir
函數是C語言中的一個庫函數,用于讀取目錄流中的條目。以下是一個簡單的示例,展示如何使用readdir
函數處理目錄及其子目錄:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
void process_directory(const char *path) {
DIR *dir;
struct dirent *entry;
dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
if (entry->d_type == DT_DIR) {
printf("Directory: %s\n", full_path);
process_directory(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;
}
process_directory(argv[1]);
return EXIT_SUCCESS;
}
這個程序接受一個命令行參數,即要處理的目錄路徑。process_directory
函數會打開目錄,然后使用readdir
函數讀取目錄中的每個條目。如果遇到子目錄,它會遞歸地調用自身來處理子目錄。對于文件,它會打印文件的完整路徑。
編譯并運行這個程序:
gcc -o list_files list_files.c
./list_files /path/to/directory
這將輸出指定目錄及其所有子目錄中的文件和文件夾。