基本上我想做与系统调用 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);
关于C++ ofstream 不会改变 mtime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10677200/