linux

Linux readdir读取文件属性的方法

小樊
49
2025-09-15 14:55:56
栏目: 智能运维

在Linux中,readdir函数用于读取目录中的文件和子目录。要使用readdir读取文件属性,你需要结合其他函数,如opendirclosedirstat。以下是一个简单的示例,展示了如何使用这些函数读取目录中的文件属性:

#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");
        return EXIT_FAILURE;
    }

    // 读取目录中的文件和子目录
    while ((entry = readdir(dir)) != NULL) {
        // 跳过当前目录(".")和上级目录("..")
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // 获取文件的完整路径
        char path[1024];
        snprintf(path, sizeof(path), "./%s", entry->d_name);

        // 获取文件属性
        if (stat(path, &file_stat) == -1) {
            perror("stat");
            continue;
        }

        // 输出文件名和文件类型
        printf("%s: ", entry->d_name);
        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("Unknown\n");
        }

        // 输出其他文件属性,如文件大小、修改时间等
        printf("Size: %ld bytes\n", file_stat.st_size);
        printf("Last modified: %s", ctime(&file_stat.st_mtime));
    }

    // 关闭目录
    closedir(dir);

    return EXIT_SUCCESS;
}

这个示例程序首先打开当前目录(.),然后使用readdir函数读取目录中的每个条目。对于每个条目,它使用stat函数获取文件的属性,并根据文件类型输出相应的信息。最后,它关闭目录并退出。

注意:在实际应用中,你可能需要根据实际需求对示例代码进行调整。

0
看了该问题的人还看了