14.1 文件时间

  存在于 stat 结构体中

  

14.2 文件时间函数

14.2.1 介绍

  utime(修改文件的存取时间和更改时间)
  相关函数 utimes,stat

 #include <sys/types.h>
#include <utime.h>
int utime(const char * filename, struct utimbuf * buf);
  • 函数功能

    • 更改文件的存取和修改时间
    • utime 会自动更新 st_ctime 的值
  • 参数 buf
    • 空指针:则取当前时间

      • 进程的有效用户 ID 必须等于该文件的所有者ID
      • 或者进程对该文件具有写权限
    • 非空:取 utimebuf 结构体中的时间
      • 进程有效用户ID 等于该文件的所有者ID
      • 或者进程是超级用户进程    
  • 返回值
    • 如果参数buf为空指针(NULL),则该文件的存取时间和更改时间全部会设为目前时间。
    • 执行成功则返回 0,失败返回-1,错误代码存于errno。
  • 错误代码
    • EACCESS 存取文件时被拒绝,权限不足
    • ENOENT 指定的文件不存在。
 结构体 utimbuf 定义如下
struct utimbuf{
time_t actime;  //访问时间
time_t modtime;  //修改时间
};

14.2.3 例子

  file_time.c

 #include <time.h>
#include <sys/types.h>
#include <utime.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <memory.h> // ctime 函数 将事件转换成字符串输出
void out(struct stat buff)
{
time_t val_atime = (time_t)buff.st_atime;
time_t val_mtime = (time_t)buff.st_mtime;
time_t val_ctime = (time_t)buff.st_ctime;
printf("atime: %s\n", ctime(&val_atime));
printf("mtime: %s\n", ctime(&val_mtime));
printf("ctime: %s\n", ctime(&val_ctime));
} //获取文件属性信息
struct stat get_stat(char *file, struct stat buff)
{
memset(&buff, , sizeof(buff));
if(lstat(file, &buff) < ) {
perror("lstat error");
exit();
} return buff;
} int main(int argc, char *argv[])
{
if(argc < ) {
fprintf(stderr, "usage:%s file\n", argv[]);
exit();
} struct stat buff;
buff = get_stat(argv[], buff); //备份原先的时间
struct stat bak_stat = buff;
out(buff);
printf("=============================\n"); //设置文件的事件为当前系统时间
utime(argv[], NULL);
buff = get_stat(argv[], buff);
out(buff);
printf("=============================\n"); //把文件的时间恢复成之前的时间
struct utimbuf timebuf;
timebuf.actime = bak_stat.st_atime;
timebuf.modtime = bak_stat.st_mtime;
utime(argv[], &timebuf);
buff = get_stat(argv[], buff);
out(buff); return ;
}

  编译执行:

  

  ctime 的时间是 i 节点的最后更改时间,只要调用了 utime 就会自动修改  ctime。

最新文章

  1. Haxe是何物?
  2. .NET Memory Profiler 查看内存使用情况
  3. js 运算符
  4. android 补间动画和Animation
  5. AloneJs.msgbox() —— 弹出消息框
  6. Linux Crontab 定时任务 命令详解
  7. hdu 4762 Cut the Cake (大数乘法)
  8. Android 全屏显示-隐藏Navigation Bar
  9. HDU 4196 Remoteland
  10. 那些年被我坑过的Python——不得不知(第二章)
  11. .net邮件发送实例 邮件内容为网页模板
  12. C# - 创建List属性的简单方法
  13. InstallShield自定义安装界面
  14. Myeclipse2014中,新建部署Maven项目
  15. 存图方式---邻接表&amp;邻接矩阵&amp;前向星
  16. 【原】无脑操作:EasyUI Tree实现左键只选择叶子节点、右键浮动菜单实现增删改
  17. Python Selenium set Chrome Preference Download Location.
  18. CCommandLineInfo类
  19. Redis配置文件介绍
  20. WebBrowserのIEバージョンを最新にする。

热门文章

  1. 使用ajax实现前后端是数据交互
  2. Nginx安装,操作简单
  3. poj2054 Color a Tree
  4. 【洛谷P2585】三色二叉树
  5. C#两个实体之间相同属性的映射
  6. 自制模态窗体闪烁效果: MessageBeep &amp; FlashWindowEx
  7. Vue+koa2开发一款全栈小程序(3.vue入门、Mpvue入门)
  8. Linux提取不匹配字符串的行和列(awk函数)
  9. 【译】12. Java反射——类的动态加载和重新加载
  10. ElasticSearch6.5.0 【安装IK分词器】