在Debian系统中,readdir
函数通常用于读取目录中的文件和子目录
sudo apt-get update
sudo apt-get install build-essential
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;
}
这段代码会读取指定目录中的所有文件和子目录,并输出它们的名称、大小和最后修改时间。
gcc readdir_example.c -o readdir_example
./readdir_example /path/to/directory
程序将输出指定目录中所有文件和子目录的名称、大小和最后修改时间。