溫馨提示×

Linux readdir如何處理文件屬性

小樊
48
2025-04-16 12:45:31
欄目: 智能運維

在Linux中,readdir函數用于讀取目錄中的條目。當你使用readdir函數時,它會返回一個指向dirent結構體的指針,該結構體包含了目錄條目的信息,如文件名、文件類型等。要處理文件屬性,你可以使用stat函數來獲取文件的詳細信息。

以下是一個簡單的示例,展示了如何使用readdirstat函數來處理文件屬性:

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

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

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
        return 1;
    }

    // 打開目錄
    dir = opendir(argv[1]);
    if (dir == NULL) {
        perror("opendir");
        return 1;
    }

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

        // 構建文件的完整路徑
        snprintf(path, sizeof(path), "%s/%s", argv[1], 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));
        printf("File type: ");
        if (S_ISREG(file_stat.st_mode)) {
            printf("Regular file\n");
        } else if (S_ISDIR(file_stat.st_mode)) {
            printf("Directory\n");
        } else if (S_ISCHR(file_stat.st_mode)) {
            printf("Character device\n");
        } else if (S_ISBLK(file_stat.st_mode)) {
            printf("Block device\n");
        } else if (S_ISFIFO(file_stat.st_mode)) {
            printf("FIFO\n");
        } else if (S_ISSOCK(file_stat.st_mode)) {
            printf("Socket\n");
        } else {
            printf("Other\n");
        }
    }

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

這個示例程序接受一個目錄作為命令行參數,然后使用readdir函數讀取目錄中的條目。對于每個條目,它使用stat函數獲取文件的詳細信息,并根據文件類型打印相應的屬性。

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