linux

Linux readdir如何处理文件属性

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