温馨提示×

如何使用Debian readdir获取文件属性

小樊
49
2025-03-14 13:15:41
栏目: 智能运维

在Debian系统中,readdir函数通常用于读取目录中的文件和子目录

  1. 首先,确保你的系统已经安装了C编译器。如果没有,请运行以下命令安装:
sudo apt-get update sudo apt-get install build-essential 
  1. 创建一个名为readdir_example.c的C文件,并在其中编写以下代码:
#include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <sys/stat.h> #include <unistd.h> int main(int argc, char *argv[]) { DIR *dir; struct dirent *entry; struct stat file_stat; if (argc != 2) { printf("Usage: %s <directory_path>\n", argv[0]); return 1; } dir = opendir(argv[1]); if (dir == NULL) { perror("opendir"); return 1; } while ((entry = readdir(dir)) != NULL) { char path[PATH_MAX]; snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name); if (stat(path, &file_stat) == -1) { perror("stat"); continue; } printf("Name: %s\n", entry->d_name); printf("Size: %ld bytes\n", file_stat.st_size); printf("Last modified: %s", ctime(&file_stat.st_mtime)); printf("\n"); } closedir(dir); return 0; } 

这段代码会读取指定目录中的所有文件和子目录,并输出它们的名称、大小和最后修改时间。

  1. 使用C编译器编译代码:
gcc readdir_example.c -o readdir_example 
  1. 运行编译后的程序,传入要读取的目录路径作为参数:
./readdir_example /path/to/directory 

程序将输出指定目录中所有文件和子目录的名称、大小和最后修改时间。

0