为什么我不能改变最后的写入时间'我新创建的文件?

时间:2016-07-02 08:16:32

标签: c++ chrono boost-filesystem c++17

首先,我使用Visual Studio 2015实现的即将推出的基于Boost :: Filesystem的C ++ 17标准的Filesystem库。

基本上,我尝试做的是保存文件的时间戳(它的最后写入时间"),将该文件的内容复制到存档以及所述时间戳,然后将该文件提取出来并使用保存的时间戳恢复正确的"最后写入时间"。

// Get the file's 'last write time' and convert it into a usable integer.
__int64 timestamp = chrono::time_point_cast<chrono::seconds>(fs::last_write_time(src)).time_since_epoch().count();

// ... (do a bunch of stuff in here)

//  Save the file
ofstream destfile(dest, ios::binary | ios::trunc);
destfile.write(ptr, size);

// Correct the file's 'last write time'
fs::last_write_time(dest, chrono::time_point<chrono::system_clock>(chrono::seconds(timestamp)));

问题是新文件总是以一个等于创建时间的时间戳结束(现在),因为我从来没有调用last_write_time()

当我尝试将时间戳从一个现有文件复制到另一个文件时,它可以正常工作。当我从文件中复制时间戳时,使用fs::copy创建该文件的新副本,然后立即更改副本的时间戳,它也可以正常工作。以下代码正常工作:

// Get the file's 'last write time' and convert it into a usable integer.
__int64 timestamp = chrono::time_point_cast<chrono::seconds>(fs::last_write_time("test.txt")).time_since_epoch().count();
fs::copy("test.txt", "new.txt");
// Correct the file's 'last write time'
fs::last_write_time("new.txt", chrono::time_point<chrono::system_clock>(chrono::seconds(timestamp)));

我没有理由怀疑存储时间戳可能不正确,但我没有其他想法。可能导致这种情况的原因是什么?

1 个答案:

答案 0 :(得分:5)

这是因为您写入了流但在实际更新时间之前没有关闭文件。时间将在结束时再次更新。

解决方案是关闭流,然后更新文件时间。

相关问题