温馨提示×

Linux copendir如何获取文件属性信息

小樊
38
2026-01-01 19:17:01
栏目: 智能运维

在 Linux 中,copendir() 函数用于打开一个目录流,以便你可以使用 readdir() 函数读取目录中的条目。然而,copendir() 本身并不直接提供获取文件属性的功能。要获取文件属性,你需要结合其他函数,如 stat()fstat()

以下是一个示例,展示了如何使用 copendir()readdir()stat() 函数来获取目录中文件的属性信息:

#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;
    char path[1024];

    // 打开目录
    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;
        }

        // 构建文件的完整路径
        snprintf(path, sizeof(path), "./%s", entry->d_name);

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

        // 输出文件属性信息
        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));
    }

    // 关闭目录
    closedir(dir);
    return EXIT_SUCCESS;
}

这个示例程序首先使用 opendir() 打开当前目录,然后使用 readdir() 读取目录中的每个条目。对于每个条目,我们构建文件的完整路径,并使用 stat() 函数获取文件的属性信息。最后,我们输出文件的大小和最后修改时间。

0