文件时间与系统时间

来源:互联网 发布:淘宝新店铺如何推广 编辑:程序博客网 时间:2024/06/06 08:28

每个文件是有三个时间的,分别是st_atime,st_mtime和st_ctime。

st_atime: 最后一次访问时间,如果使用read函数读某个文件,会改变文件的这个时间

st_mtime:最后一次修改时间,如果使用write函数写某个文件,会改变文件的这个时间

st_ctime:最后一次修改文件权限时间,如果使用chmod修改了文件的权限,会改变这个时间


怎样获取这三个时间呢?

使用stat族函数,man 2 stat可以查看这一族函数,有stat,fstat,lstat

       int stat(const char *path, struct stat *buf);       int fstat(int fd, struct stat *buf);       int lstat(const char *path, struct stat *buf);从函数原型可知,stat函数第一个参数需要一个地址,第二个参数需要一个结构体指针,下面我们写个程序来获取当前文件的mtime, 同时获取当前的系统时间.
int main(void){    struct stat stbuf;                  //这个结构体可以man 2 stat的手册中看到,有详细成员列表    struct tm filetime;                 //这个是存放时间的结构体,用来存放文件的时间,man localtime可以                                        //看到该结构体里的详细内容    struct tm nowtime;                  //存放当前系统时间    time_t now;                         //time_t其实是长整型,用来存放时间    int fd;                             //文件描述符    //stat("./test", &stbuf);           //可以使用这种方式将文件信息存放到stbuf中    fd = open("./test", O_RDONLY);      //也可以用这种间接的方式    if(fd < 0)    {           perror("open");        return -1;     }       fstat(fd, &stbuf);    localtime_r(&stbuf.st_mtime, &filetime);//使用localtime_r函数将文件的mtime存放到filetime中    time(&now);                             //获取当前系统时间    localtime_r(&now, &nowtime);            //将系统时间存放到nowtime中    printf("file tm_min is [%d] tm_sec is [%d]\n", filetime.tm_min, filetime.tm_sec, filetime);    printf("now tm_min is [%d] tm_sec is [%d]\n", nowtime.tm_min, nowtime.tm_sec, nowtime);    return 0;}

其中的localtime_r是将time_t的时间转化为tm结构体的时间,更方便我们阅读,且存储在我们要求的地址中
还有另一个函数localtime,功能是一样的,但是它只有一个参数,它会自动分配一个空间存放转化为tm结构体的时间
这样就会遇到一个问题,如果要使用两次或以上localtime,只能保存最后一个调用函数时转化的时间!

另外stat可以获取大量有关文件的信息,可以自行查阅manpage