溫馨提示×

ubuntu下如何用copendir遍歷目錄

小樊
39
2025-03-17 10:01:07
欄目: 智能運維

在 Ubuntu 下,你可以使用 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");
        exit(EXIT_FAILURE);
    }

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

    // 關閉目錄
    closedir(dir);

    return 0;
}

將上述代碼保存為 list_directory.c,然后在終端中運行以下命令編譯和執行:

gcc list_directory.c -o list_directory
./list_directory

這將輸出當前目錄下的所有文件和子目錄。

如果你想遍歷其他目錄,只需將 opendir(".") 中的 "." 替換為你想要遍歷的目錄路徑,例如:

dir = opendir("/path/to/your/directory");

請注意,這個示例代碼僅適用于 C 語言。如果你需要在其他編程語言中實現類似的功能,請查閱相應語言的文檔。

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