gpt4 book ai didi

c - 如何显示 st_atime 和 st_mtime

转载 作者:IT王子 更新时间:2023-10-29 01:22:15 26 4
gpt4 key购买 nike

我想从结构stat中显示我的两个属性

struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for file system I/O */
blkcnt_t st_blocks; /* number of 512B blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last status change */

};

这是我的代码,我尝试显示最后一次访问和最后一次修改文件夹/文件的时间

struct tm *time;
char buffer[200];
time = localtime(file_info.st_atime);
strftime(buffer, sizeof(buffer), "%d.%m.%Y %H:%M:%S", time);
printf("%s\n", buffer);
time = localtime(file_info.st_mtime);
strftime(buffer, sizeof(buffer), "%d.%m.%Y %H:%M:%S", time);
printf("%s\n", buffer);

我想显示像 15.03.1952 23:11:34 这样的人类可读时间和日期,该文件夹/文件信息已被最后修改或在 linux 中访问

最佳答案

这在风格方面与您的代码有点偏差,但也许它有帮助?

#include <time.h>
#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>

char* formatdate(char* str, time_t val)
{
strftime(str, 36, "%d.%m.%Y %H:%M:%S", localtime(&val));
return str;
}

int main()
{
int errno;
const char* filename;
filename = "stat.c";

errno = 0;
struct stat *file_info = malloc(sizeof(struct stat));
if (lstat(filename, file_info) != 0) {
perror("Error");
exit(1);
}

char date[36];
printf("Access: %s\n", formatdate(date, file_info->st_atime));
printf("Modify: %s\n", formatdate(date, file_info->st_mtime));
printf("Change: %s\n", formatdate(date, file_info->st_ctime));
free(file_info);
return 0;
}

关于c - 如何显示 st_atime 和 st_mtime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26306644/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com