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