溫馨提示×

如何用copendir獲取目錄文件屬性

小樊
43
2025-04-02 08:57:06
欄目: 編程語言

opendir() 函數用于打開一個目錄流,而不是直接獲取目錄文件的屬性。要獲取目錄文件的屬性,你需要結合使用 readdir() 和其他相關函數。以下是一個簡單的示例,展示了如何使用 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;

    // 打開目錄
    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;
        }

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

        // 獲取文件的屬性
        if (stat(file_path, &file_stat) == -1) {
            perror("stat");
            closedir(dir);
            return EXIT_FAILURE;
        }

        // 輸出文件屬性
        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() 逐個讀取目錄中的條目。對于每個條目,我們使用 snprintf() 構建文件的完整路徑,然后使用 stat() 獲取文件的屬性。最后,我們輸出文件的大小和最后修改時間。

注意:這個示例程序僅適用于類 Unix 系統(如 Linux 和 macOS)。在 Windows 上,你需要使用 Windows API 函數(如 FindFirstFile()、FindNextFile()GetFileInformationByHandle())來實現類似的功能。

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