在 CentOS 系统中,readdir 函数本身并不直接提供文件的创建时间。readdir 函数主要用于读取目录中的条目。然而,你可以使用其他方法来获取文件的创建时间。以下是一些方法:
stat 函数你可以使用 stat 函数来获取文件的详细信息,包括创建时间。以下是一个示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <dirent.h>
#include <time.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return EXIT_FAILURE;
}
DIR *dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
struct stat file_stat;
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
char time_buf[20];
strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", localtime(&file_stat.st_ctime));
printf("%s %s\n", entry->d_name, time_buf);
}
closedir(dir);
return EXIT_SUCCESS;
}
在这个示例中,stat 函数用于获取文件的详细信息,st_ctime 字段表示文件的创建时间。
ls 命令如果你只是想在命令行中查看文件的创建时间,可以使用 ls 命令的 -l 选项,并结合 -t 选项按修改时间排序:
ls -lt --time=creation
注意:并非所有的文件系统都支持文件的创建时间(ctime),在某些文件系统中,ctime 可能表示状态改变时间。
find 命令如果你想查找特定目录下的文件并显示它们的创建时间,可以使用 find 命令:
find /path/to/directory -type f -exec ls -lt --time=creation {} \;
同样,注意 ctime 可能表示状态改变时间。
通过这些方法,你可以在 CentOS 系统中获取文件的创建时间。