debian

debian readdir如何获取文件属性

小樊
44
2025-06-23 09:37:20
栏目: 智能运维

在 Debian 系统中,你可以使用 readdir 函数来读取目录中的文件和子目录。如果你想要获取这些文件和子目录的属性,你可以结合使用 stat 函数。

以下是一个简单的示例代码,演示了如何使用 readdirstat 来获取目录中每个文件的属性:

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

        // 输出文件名和大小
        printf("Name: %s\n", entry->d_name);
        printf("Size: %ld bytes\n", file_stat.st_size);
        
        // 你可以根据需要输出更多属性,例如:
        printf("Type: %s\n", S_ISREG(file_stat.st_mode) ? "Regular file" : "Directory");
        printf("Last modified: %s", ctime(&file_stat.st_mtime));
    }

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

代码说明:

  1. 打开目录:使用 opendir 打开当前目录(.)。
  2. 读取目录条目:使用 readdir 遍历目录中的每个条目。
  3. 构建文件路径:将目录条目与路径前缀拼接成完整路径。
  4. 获取文件属性:使用 stat 函数获取文件的详细信息,并存储在 struct stat 结构体中。
  5. 输出文件属性:可以根据需要输出文件的大小、类型、最后修改时间等信息。

注意事项:

0
看了该问题的人还看了