溫馨提示×

CentOS readdir如何獲取文件屬性

小樊
45
2025-03-27 20:19:43
欄目: 智能運維

在 CentOS 系統中,你可以使用 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");
        exit(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");
            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 0;
}

這個示例程序首先打開當前目錄(.),然后使用 readdir 函數讀取目錄中的每個文件。對于每個文件,它使用 stat 函數獲取文件的屬性,并輸出文件名、大小和最后修改時間。

請注意,這個示例程序僅用于演示目的,實際應用中可能需要根據需求進行相應的修改。

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