文件的状态中,维护着三个时间,分别是:
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到自己定义的字符数组中。