在Debian系統中,readdir
函數用于讀取目錄中的條目。當使用readdir
處理子目錄時,需要遞歸地遍歷目錄結構。以下是一個簡單的示例,展示了如何使用readdir
處理子目錄:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void process_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) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
char full_path[1024];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
if (lstat(full_path, &statbuf) == -1) {
perror("lstat");
continue;
}
if (S_ISDIR(statbuf.st_mode)) {
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 1;
}
process_directory(argv[1]);
return 0;
}
這個程序接受一個目錄作為參數,然后使用readdir
函數讀取目錄中的條目。對于每個條目,它會檢查是否為子目錄。如果是子目錄,程序會遞歸地調用process_directory
函數來處理子目錄。如果不是子目錄,程序將輸出文件名。
請注意,這個示例沒有處理符號鏈接和其他可能的錯誤情況。在實際應用中,你可能需要根據你的需求進行相應的調整。