debian

如何在Debian中使用readdir获取文件属性

小樊
36
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
看了该问题的人还看了