在 CentOS 系统中,你可以使用 readdir
函数来读取目录中的文件,并使用 stat
函数来获取文件的属性。以下是一个简单的示例,展示了如何使用这两个函数来获取目录中文件的属性:
#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");
exit(EXIT_FAILURE);
}
// 读取目录中的文件
while ((entry = readdir(dir)) != NULL) {
// 跳过当前目录和上级目录
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 获取文件的完整路径
char file_path[1024];
snprintf(file_path, sizeof(file_path), "./%s", entry->d_name);
// 获取文件属性
if (stat(file_path, &file_stat) == -1) {
perror("stat");
continue;
}
// 输出文件属性
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));
}
// 关闭目录
closedir(dir);
return 0;
}
这个示例程序首先打开当前目录(.
),然后使用 readdir
函数读取目录中的每个文件。对于每个文件,它使用 stat
函数获取文件的属性,并输出文件名、大小和最后修改时间。
请注意,这个示例程序仅用于演示目的,实际应用中可能需要根据需求进行相应的修改。