溫馨提示×

如何在Debian中使用readdir獲取文件屬性

小樊
49
2025-04-27 18:57:32
欄目: 智能運維

在Debian中,使用readdir函數獲取文件屬性需要包含頭文件dirent.hsys/stat.h

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.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 name: %s\n", entry->d_name);
        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");
        }

        // 輸出文件大小
        printf("File size: %ld bytes\n", file_stat.st_size);
    }

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

這個示例程序會列出當前目錄下的所有文件和文件夾,并顯示它們的類型和大小。你可以根據需要修改這個程序,以便獲取其他文件屬性或處理其他目錄。

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