gpt4 book ai didi

C++ ofstream 不会改变 mtime

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:55:17 24 4
gpt4 key购买 nike

基本上我想做与系统调用 touch 相同的事情(如果文件不存在则创建文件,如果存在则更新其修改时间戳)。

std::string file = ...;
std::ofstream(file.c_str(), std::ios::app);

如果文件不存在,这将创建该文件。但不会改变修改时间。

std::string file = ...;
std::ofstream(file.c_str(), std::ios::out);

如果文件不存在,这将创建它,如果存在,它将更新修改时间,但如果文件存在,它也会截断文件。

那么我该如何触摸一个文件呢?

最佳答案

Kerrek SB 已发布解决方案,但不幸的是在 comment 中而不是答案(我宁愿接受他的回答)。

我在 utime(2) 上取得了成功:

#include <utime.h>
...
std::string path = "/path/to/my/file";
bool success = !utime(path.c_str(), 0);

大卫·施瓦茨 mentioned utimensat纳秒精度。

关于C++ ofstream 不会改变 mtime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10677200/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com