Why can't I change the 'last write time' of my newly created files?

◇◆丶佛笑我妖孽 提交于 2019-12-31 05:19:05

问题


First off, I'm using Visual Studio 2015's implementation of the Filesystem library from the upcoming C++17 standard, which is based on Boost::Filesystem.

Basically, what I'm trying to do is save a file's timestamp (it's "last write time"), copy that file's contents into an archive along with said timestamp, then extract that file back out and use the saved timestamp to restore the correct "last write time".

// 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)));

The problem is that the new file will always end up with a timestamp equaling the time it was created (right now), as it I never called last_write_time() at all.

When I try copying the timestamp from one existing file to another, it works fine. When I copy the timestamp from a file, then use fs::copy to create a new copy of that file, then immediately change the copy's timestamp, it also works fine. The following code works correctly:

// 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)));

I have no reason to suspect that storing the timestamp could be incorrect, but I have no other ideas. What might be causing this?


回答1:


This happens because you wrote to the stream but didn't close the file before actually updating the time. The time will be updated again on close.

The solution is to close the stream and then update the file time.



来源:https://stackoverflow.com/questions/38158037/why-cant-i-change-the-last-write-time-of-my-newly-created-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!