《unix高级环境编程》文件和目录——文件时间

来源:互联网 发布:苹果笔记本忘记mac密码 编辑:程序博客网 时间:2024/05/12 23:47
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /********** 
  2.  * 文件时间 
  3.  * 根据stat的结构可以知道,文件有三种时间: 
  4.  * st_atime     最后访问时间,即最后访问文件的时间 
  5.  * st_mtime     最后修改时间,即修改文件内容的时间 
  6.  * st_ctime     最后更改时间,即更改inode节点的时间 
  7.  * ****/  
  8. /********** 
  9.  * utime函数 
  10.  * 函数功能:更改文件访问时间和文件修改时间; 
  11.  * 返回值:若成功则返回0,若出错则返回-1; 
  12.  * 函数原型: 
  13.  * int utime(const char *pathname, const struct utimbuf *times); 
  14.  * 其中结构体struct utimbuf 定义如下: 
  15.  * struct utimbuf{ 
  16.  *      time_t actime;// access time  
  17.  *      time_t modtime;// modification time 
  18.  *      }; 
  19.  *  参数说明: 
  20.  *  pathname是要更改时间的文件; 
  21.  *  times若为空指针,则表示设置为当前时间; 
  22.  *  若times非空指针,则设置为所指向结构体中的对应值; 
  23.  *  ********/  
  24.   
  25. #include "apue.h"  
  26. #include <fcntl.h>  
  27. #include <utime.h>  
  28.   
  29. int main(int argc, char *argv[])  
  30. {  
  31.     int i,fd;  
  32.     struct stat statbuf;  
  33.     struct utimbuf timebuf;  
  34.   
  35.     for(i=1;i<argc;i++)  
  36.     {  
  37.         if(stat(argv[i],&statbuf) < 0){  
  38.             err_ret("%s:stat error.\n",argv[i]);  
  39.             continue;  
  40.         }  
  41.         if((fd = open(argv[i],O_RDWR | O_TRUNC)) < 0){  
  42.             err_ret("%s:open error.\n",argv[i]);  
  43.             continue;  
  44.         }  
  45.         close(fd);  
  46.         timebuf.actime = statbuf.st_atime;  
  47.         timebuf.modtime = statbuf.st_mtime;  
  48.         if(utime(argv[i],&timebuf) < 0){  
  49.             err_ret("%s:utime error.\n",argv[i]);  
  50.             continue;  
  51.         }  
  52.     }  
  53.     exit(0);  
  54. }  
0 0
原创粉丝点击