如何显示st_atime和st_mtime

时间:2014-10-10 19:23:20

标签: c linux

我想在结构属性

中显示我的两个属性
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中访问的文件夹/文件信息

3 个答案:

答案 0 :(得分:4)

这在风格方面偏离了你的代码,但也许它有用吗?

#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;
}

答案 1 :(得分:0)

        char buffer[200];

    printf("Access : %s\n", formatdate(buffer, file_info.st_atime));
    printf("Modify : %s\n", formatdate(buffer, file_info.st_mtime));
    printf("\n\n");




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

这就是我再次感谢的答案。

答案 2 :(得分:0)

试试这个:printf("%s", asctime(localtime(&buffer.st_mtime)));