溫馨提示×

Debian readdir如何處理子目錄

小樊
48
2025-03-02 10:56:38
欄目: 智能運維

在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函數來處理子目錄。如果不是子目錄,程序將輸出文件名。

請注意,這個示例沒有處理符號鏈接和其他可能的錯誤情況。在實際應用中,你可能需要根據你的需求進行相應的調整。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女