linux

copendir如何获取文件属性

小樊
33
2025-07-18 09:24:11
栏目: 编程语言

copendir 函数本身并不直接提供获取文件属性的功能。它的主要作用是打开一个目录流,以便你可以使用 readdir 函数来读取目录中的条目。

如果你想要在遍历目录的同时获取文件属性,你可以结合使用 opendir(或 scandir)、readdirstat 函数。以下是一个简单的示例,展示了如何使用这些函数来获取目录中文件的属性:

#include <stdio.h>
#include <stdlib.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");
        return EXIT_FAILURE;
    }

    while ((entry = readdir(dir)) != NULL) {
        // 跳过当前目录和上级目录的特殊条目
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // 构建文件的完整路径
        char path[PATH_MAX];
        snprintf(path, sizeof(path), "./%s", 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));
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

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

注意:在实际应用中,你可能需要根据实际需求对代码进行调整,例如处理符号链接、错误处理等。

0
看了该问题的人还看了