在Linux中,你可以使用readdir
函數來遞歸遍歷目錄。以下是一個簡單的示例,展示了如何使用readdir
函數遞歸遍歷目錄及其子目錄:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
void list_directory_contents(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;
}
snprintf(path_stat.path, sizeof(path_stat.path), "%s/%s", path, entry->d_name);
if (stat(path_stat.path, &path_stat) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(path_stat.st_mode)) {
printf("Directory: %s\n", path_stat.path);
list_directory_contents(path_stat.path);
} else {
printf("File: %s\n", path_stat.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
函數;如果是文件,則打印文件名。
要編譯此程序,請將其保存為list_directory_contents.c
,然后運行以下命令:
gcc -o list_directory_contents list_directory_contents.c
現在,你可以使用以下命令運行程序,其中<directory>
是要遍歷的目錄路徑:
./list_directory_contents <directory>
請注意,這個示例程序沒有處理符號鏈接、權限問題和其他潛在的錯誤情況。在實際應用中,你可能需要根據你的需求對其進行修改。