在 Debian 系統中,你可以使用 readdir 函數來遍歷目錄及其子目錄。readdir 是一個 POSIX 標準庫函數,用于讀取目錄流中的條目。下面是一個使用 C 語言編寫的示例程序,演示如何使用 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;
}
printf("%s\n", path_stat_path);
if (S_ISDIR(path_stat.st_mode)) {
list_directory_contents(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.c,然后在終端中運行以下命令:
gcc -o list_directory_contents list_directory_contents.c
現在,你可以使用以下命令運行程序,列出指定目錄及其子目錄的內容:
./list_directory_contents /path/to/directory
請注意,這個示例程序僅適用于 POSIX 兼容的系統,如 Debian。在其他系統上,可能需要使用不同的函數和方法。