溫馨提示×

如何在Debian中使用readdir獲取文件路徑

小樊
42
2025-05-22 00:12:25
欄目: 智能運維

在Debian中,你可以使用C語言的dirent.h庫中的readdir()函數來獲取目錄中的文件路徑

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

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

    // 打開目錄
    dir = opendir("/path/to/your/directory");
    if (dir == NULL) {
        perror("opendir");
        exit(EXIT_FAILURE);
    }

    // 讀取目錄中的文件和子目錄
    while ((entry = readdir(dir)) != NULL) {
        // 獲取文件路徑
        char filepath[1024];
        snprintf(filepath, sizeof(filepath), "%s/%s", "/path/to/your/directory", entry->d_name);

        // 打印文件路徑
        printf("%s\n", filepath);
    }

    // 關閉目錄
    closedir(dir);

    return 0;
}

/path/to/your/directory替換為你想要獲取文件路徑的目錄。編譯并運行此程序,它將輸出該目錄中的所有文件和子目錄的路徑。

編譯示例:

gcc -o list_files list_files.c

運行示例:

./list_files

請注意,這個示例程序僅適用于Debian和其他類Unix系統。如果你需要在其他操作系統上實現類似的功能,你可能需要使用不同的庫和函數。

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