linux

如何使用copendir获取文件属性

小樊
40
2025-12-26 22:34:02
栏目: 编程语言

copendir 函数用于打开一个目录流,以便遍历目录中的文件和子目录

  1. 包含头文件:
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
  1. 打开目录:
DIR *dir = opendir("your_directory_path");
if (dir == NULL) {
    perror("opendir");
    exit(EXIT_FAILURE);
}
  1. 遍历目录中的文件和子目录:
struct dirent *entry;
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/%s", "your_directory_path", entry->d_name);

    // 获取文件属性
    struct stat file_stat;
    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("Permissions: %o\n", file_stat.st_mode);
    printf("Last modified: %s", ctime(&file_stat.st_mtime));
}
  1. 关闭目录:
closedir(dir);

这个示例将遍历指定目录中的所有文件和子目录,并输出它们的大小、权限和最后修改时间。你可以根据需要修改代码以获取其他文件属性。

0
看了该问题的人还看了