温馨提示×

Linux readdir支持哪些文件属性

小樊
46
2025-09-11 14:42:31
栏目: 智能运维

readdir 是 Linux 系统中的一个函数,用于读取目录中的文件和子目录。它返回一个指向 dirent 结构体的指针,其中包含了文件或子目录的信息。dirent 结构体中定义了一些文件属性字段,主要包括以下几种:

dirent 结构体中的主要字段

  1. d_ino:

    • 文件或目录的 inode 号。
    • 唯一标识文件系统中的一个文件或目录。
  2. d_off:

    • 在目录文件中的偏移量。
    • 用于下次读取时定位到正确的位置。
  3. d_reclen:

    • dirent 结构体的长度。
    • 用于解析结构体时的字节对齐。
  4. d_name:

    • 文件或目录的名称。
    • 最多可以包含 256 个字符。

其他相关属性(通过 stat 函数获取)

虽然 readdir 本身不直接提供所有文件属性,但可以通过结合使用 stat 函数来获取更详细的文件信息。stat 函数返回一个 stat 结构体,其中包含了丰富的文件属性,例如:

  • st_mode: 文件类型和权限。
  • st_ino: 文件的 inode 号。
  • st_dev: 文件所在的设备号。
  • st_nlink: 文件的硬链接数。
  • st_uid: 文件所有者的用户 ID。
  • st_gid: 文件所有者的组 ID。
  • st_size: 文件的大小(字节)。
  • st_atime: 最后访问时间。
  • st_mtime: 最后修改时间。
  • st_ctime: 最后状态改变时间。
  • st_blocks: 文件占用的磁盘块数。
  • st_flags: 文件系统特定的标志。
  • st_gen: 文件的生成号(用于某些文件系统)。

示例代码

以下是一个简单的示例,展示如何使用 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; char path[1024]; dir = opendir("."); if (dir == NULL) { perror("opendir"); return EXIT_FAILURE; } while ((entry = readdir(dir)) != NULL) { if (entry->d_type == DT_REG) { // 只处理普通文件 snprintf(path, sizeof(path), "./%s", entry->d_name); if (stat(path, &file_stat) == 0) { 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)); // 可以打印更多属性... } else { perror("stat"); } } } closedir(dir); return EXIT_SUCCESS; } 

这个程序会遍历当前目录下的所有普通文件,并打印出它们的大小和最后修改时间。

总之,readdir 主要提供了文件名和一些基本信息,而更详细的文件属性需要通过 stat 函数来获取。

0