在Linux系統中,readdir
函數本身并不支持遞歸讀取目錄
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.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) {
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
if (stat(full_path, &path_stat) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(path_stat.st_mode)) {
if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
list_directory_contents(full_path);
}
} else {
printf("%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
函數首先打開目錄,然后使用readdir
讀取目錄中的每個條目。對于每個條目,它使用stat
函數獲取文件的狀態信息,然后檢查是否為目錄。如果是目錄(并且不是當前目錄.
或上級目錄..
),則遞歸調用list_directory_contents
。如果不是目錄,則打印文件的完整路徑。
要編譯此程序,請將其保存為list_dir.c
,然后運行以下命令:
gcc -o list_dir list_dir.c
現在,您可以使用以下命令運行程序:
./list_dir /path/to/directory
這將遞歸地列出指定目錄及其所有子目錄中的文件。