Linux环境,使用C语言获得文件access、modify、change的时间

文件的状态中,维护着三个时间,分别是:

last access time:最后访问时间,文件的读、写、执行等都会改变文件的最后访问时间

last modify time:最后修改时间,文件的truncate、写等都会改变文件的最后修改时间。

last modify time:最后改变时间,改变文件的拥有者user、用户组group、访问模式mode、链接数link count等都会改变文件的最后改变时间。

 

下面通过stat系统调用来获得某个文件的last access、last modify、last change时间,代码如下:

#include<time.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<stdio.h>
char* get_last_access_time(char* path)
{
    struct stat stat_buf;
    if(stat(path,&stat_buf)==0)
    {
        time_t last_access_time=stat_buf.st_atime;
        return ctime(&last_access_time);
    }
    else
        printf("path error\n");
    return NULL;
}
 
char* get_last_modify_time(char* path)
{
    struct stat stat_buf;
    if(stat(path,&stat_buf)==0)
    {
        time_t last_modify_time=stat_buf.st_mtime;
        return ctime(&last_modify_time);
    }
    else
        printf("path error\n");
    return NULL;
}
 
char* get_last_change_time(char* path)
{
    struct stat stat_buf;
    if(stat(path,&stat_buf)==0)
    {
        time_t last_change_time=stat_buf.st_ctime;
        return ctime(&last_change_time);
    }
    else
        printf("path error\n");
    return NULL;
}
int main(int* argc,char* argv[])
{
    char path[100]="";
    printf("Please input file path:\n");
    while(scanf("%s",path)!=EOF)
    {
        printf("%s",get_last_access_time(path));
        printf("%s",get_last_modify_time(path));
        printf("%s",get_last_change_time(path));
    }
    return 0;
}


以上代码片段中需要注意以下几点:

1、stat系统调用函数的返回值是0表示正确,-1表示错误。

2、st_atime、st_mtime、st_ctime的类型都是time_t,可以通过ctime将time_t类型转换成字符串类型。

3、ctime的返回值是字符串的首字母的指针,此字符串的存储位置是:静态存储区(ctime函数内部使用的static字符数组)。所以两个连续的调用ctime会把前边那个调用返回的字符串值覆盖掉,解决办法是使用strcpy把结果字符串copy到自己定义的字符数组中。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值