ubuntu

Ubuntu readdir 如何获取文件属性

小樊
42
2025-09-20 14:19:15
栏目: 智能运维

在 Ubuntu 中,你可以使用 C 语言的 dirent.h 库来读取目录中的文件,并使用 sys/stat.h 库来获取文件的属性。以下是一个简单的示例,展示了如何使用这些库来读取目录中的文件并获取它们的属性:

#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 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: %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;
}

这个示例程序会打开当前目录(.),读取其中的所有文件,并输出每个文件的名称、大小和最后修改时间。你可以根据需要修改这个程序,以便获取其他文件属性或处理其他目录。

要编译这个程序,请将其保存为 list_files.c,然后在终端中运行以下命令:

gcc list_files.c -o list_files

这将生成一个名为 list_files 的可执行文件。运行该文件,你将看到当前目录中所有文件的详细信息。

0
看了该问题的人还看了