溫馨提示×

Linux readdir如何獲取文件屬性信息

小樊
34
2025-06-14 04:12:24
欄目: 智能運維

在Linux中,readdir函數用于讀取目錄中的條目。但是,readdir本身并不直接提供文件的屬性信息。要獲取文件屬性信息,你需要使用其他函數,如stat、lstatfstat。

以下是一個簡單的示例,展示了如何使用opendir、readdirstat函數來獲取目錄中文件的屬性信息:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.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;
        }

        // 使用stat函數獲取文件屬性信息
        if (stat(entry->d_name, &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;
}

這個示例程序首先打開當前目錄,然后使用readdir函數讀取目錄中的每個條目。對于每個條目,它使用stat函數獲取文件的屬性信息,并輸出文件名、大小和最后修改時間。注意,這個示例僅適用于UNIX-like系統,如Linux。

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