为什么我不能更改新创建的文件的"上次写入时间"?

Hay*_*ach 0 c++ boost-filesystem c++-chrono c++17

首先,我使用Visual Studio 2015实现的文件系统库来自即将推出的基于Boost :: Filesystem的C++ 17标准.

基本上,我要做的是保存文件的时间戳(它是"最后写入时间"),将该文件的内容与所述时间戳一起复制到存档中,然后将该文件提取出来并使用保存的时间戳恢复正确"最后写作时间".

// 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)));
Run Code Online (Sandbox Code Playgroud)

问题是新文件总是以一个时间戳等于它创建的时间(现在),因为它根本就没有调用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)));
Run Code Online (Sandbox Code Playgroud)

我没有理由怀疑存储时间戳可能不正确,但我没有其他想法.可能是什么导致了这个?

Pau*_*ian 5

发生这种情况是因为您写入了流但在实际更新时间之前没有关闭文件.时间将在关闭时再次更新.

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