溫馨提示×

copendir在Linux中如何實現目錄遍歷

小樊
35
2025-06-26 03:09:10
欄目: 智能運維

copendir() 是一個在 Linux 系統中用于打開目錄的函數,它是 dirent.h 頭文件的一部分。要實現目錄遍歷,你需要結合使用 opendir()、readdir()closedir() 函數。下面是一個簡單的示例,展示了如何使用這些函數遍歷目錄:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>

int main() {
    DIR *dir;
    struct dirent *entry;

    // 打開目錄
    dir = opendir(".");
    if (dir == NULL) {
        perror("opendir");
        return EXIT_FAILURE;
    }

    // 遍歷目錄
    while ((entry = readdir(dir)) != NULL) {
        printf("%s\n", entry->d_name);
    }

    // 關閉目錄
    closedir(dir);

    return EXIT_SUCCESS;
}

這個示例程序會打開當前目錄(.),然后使用 readdir() 函數讀取目錄中的每個條目。對于每個條目,它將打印出條目的名稱。最后,它使用 closedir() 函數關閉目錄。

如果你想要遞歸地遍歷目錄及其子目錄,你可以編寫一個遞歸函數來實現這個功能。下面是一個簡單的遞歸目錄遍歷示例:

#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 == 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 (stat(full_path, &path_stat) == -1) {
            perror("stat");
            continue;
        }

        // 如果是目錄,則遞歸遍歷
        if (S_ISDIR(path_stat.st_mode)) {
            list_directory_contents(full_path);
        } else {
            printf("%s\n", full_path);
        }
    }

    // 關閉目錄
    closedir(dir);
}

int main() {
    list_directory_contents(".");
    return EXIT_SUCCESS;
}

這個示例程序定義了一個名為 list_directory_contents 的遞歸函數,它會遍歷指定路徑下的所有文件和目錄。對于每個目錄,它會遞歸地調用自身。

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