在 Linux 中,使用 opendir()
、readdir()
和 closedir()
函數可以遍歷目錄結構。下面是一個簡單的示例,展示了如何使用這些函數遍歷目錄結構:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
void traverse_directory(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
// 獲取文件的詳細信息
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
if (stat(full_path, &statbuf) == -1) {
perror("stat");
continue;
}
// 如果是目錄,則遞歸遍歷
if (S_ISDIR(statbuf.st_mode)) {
if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
traverse_directory(full_path);
}
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return 1;
}
traverse_directory(argv[1]);
return 0;
}
這個程序接受一個目錄路徑作為參數,并遞歸地遍歷該目錄及其子目錄。對于每個文件和目錄,它將打印其名稱。請注意,這個程序不會處理符號鏈接,也不會檢查訪問權限。在實際應用中,你可能需要根據需求對這些方面進行處理。