实现文件时间信息的打印输出

版权声明:私藏源代码是违反人性的罪恶行为!博客转载无需告知,学无止境。 https://blog.csdn.net/qq_41822235/article/details/83832140

一、 基础知识

在Linux中,没有文件创建时间的说法,只有修改时间(st_mtime)、状态更改时间(st_ctime)、最后访问时间(st_time)三种。值得注意的是,时间

图1 ls -l每一列信息的含义(以空格隔开作为一列)

ls -l打印输出的正是修改时间,在Linux下容易验证,在此不加赘述。

Linux中的时间是这样纪录的——记下距特定时间 (1970年1月1日00:00:00)(以Unix诞生的时间为参照确定的,UNIX认为1970年1月1日0点是时间纪元) 的秒数(乃至纳秒),然后经过一系列转换变成我们看到的样子。

二、 代码实现

首先,在struct stat结构(#include<sys/stat.h>)中,有一字段为st_mtime,目前精度是秒数;其次,将st_mtime交由gmtime或localtime(#include<time.h>)函数进行处理,得到struct tm(#include<time.h>)结构内容是不一样的——前者是本机时间,后者是统一时间,简单来理解:我不联网就可以把电脑的时间改成我想要的,这样,世界一个时间,我的电脑一个时间,没有一点问题。最后,调用strftime(#include<time.h>)函数对tm进行处理(类似于printf函数)。

图2 时间函数调用示意图
#include<time.h>    //strftime() localtime()
#include<sys/stat.h>	//stat()
#include<assert.h>  //assert()
#include<stdio.h>   //printf()

int main()
{
    struct stat st;
    assert(0 == stat("/home/zhaopulei/桌面/a.txt", &st));    //由stat()函数自动填写变量st。
    
    struct tm *tmp = localtime(&st.st_mtime);    //由localtime()自动返回struct tm*类型。
    assert(NULL != tmp);   
    
    char buf[64];
    assert(0 != strftime(buf, 64, "%m月 %e日 %R", tmp));    //由strftime将时间分解成字符串写入buf中。

    printf("%s\n", buf);    //打印输出结果。
    return 0;
}

代码说明,在Linux桌面上新建文件a.txt,尝试输出时间。

图3 运行结果

经过比对,和ls命令输出的结果一致,证明代码运行正确。本电脑虚拟机上安装的Linux没有联网,时间是自己的那一套。 

猜你喜欢

转载自blog.csdn.net/qq_41822235/article/details/83832140
今日推荐