为什么不能更改新创建文件的“上次写入时间”? [英] Why can't I change the 'last write time' of my newly created files?

查看:88
本文介绍了为什么不能更改新创建文件的“上次写入时间”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我使用Visual Studio 2015对即将发布的C ++ 17标准(基于Boost :: Filesystem)的Filesystem库的实现。

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

问题在于,新文件的最终时间戳总是等于创建时间(现在),因为我根本没有调用 last_write_time()

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.

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

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?

推荐答案

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

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.

这篇关于为什么不能更改新创建文件的“上次写入时间”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆