溫馨提示×

如何用copendir獲取Linux文件屬性

小樊
41
2025-09-17 10:18:39
欄目: 智能運維

在Linux中,opendir()函數用于打開一個目錄流,而不是直接獲取文件屬性。要使用opendir()獲取目錄中的文件屬性,你需要結合其他函數,如readdir()stat()。以下是一個簡單的示例,展示了如何使用這些函數獲取目錄中文件的屬性:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>

int main() {
    DIR *dir;
    struct dirent *entry;
    struct stat file_stat;
    char path[1024];

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

    // 讀取目錄中的條目
    while ((entry = readdir(dir)) != NULL) {
        // 跳過當前目錄(.)和上級目錄(..)
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // 構建文件的完整路徑
        snprintf(path, sizeof(path), "./%s", entry->d_name);

        // 獲取文件屬性
        if (stat(path, &file_stat) == -1) {
            perror("stat");
            continue;
        }

        // 輸出文件屬性
        printf("File: %s\n", entry->d_name);
        printf("Size: %ld bytes\n", file_stat.st_size);
        printf("Last modified: %s", ctime(&file_stat.st_mtime));
    }

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

這個示例程序首先使用opendir()打開當前目錄(.),然后使用readdir()讀取目錄中的每個條目。對于每個條目,我們構建文件的完整路徑,并使用stat()獲取文件屬性。最后,我們輸出文件的大小和最后修改時間。注意,這個示例僅用于演示目的,實際應用中可能需要根據需求進行相應的調整。

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