gpt4 book ai didi

c++ - 如何复制文件但触摸新拷贝上的时间戳?

转载 作者:行者123 更新时间:2023-11-30 01:51:07 25 4
gpt4 key购买 nike

我正在使用 ::CopyFile() 来制作文件的拷贝。看来原始文件的时间戳已被保留,我希望拷贝在拷贝上设置当前时间戳,即“触摸”它。

是否有 WinAPI 方法可以轻松做到这一点?

最佳答案

如果您阅读 MSDN documentation对于 CopyFile(),底部有注释,内容如下:

File times semantics
This article should document semantics with respect to file creation/modification/access times.

Creation time: if the target file already exists, its' creation time is preserved, otherwise it is set to the current system time.
Last Modification time: always copied from modification time of the source file.
Last Access time: always set to the current system time.

Mod-time not always preserved
The modification time is not guaranteed to be set. CopyFileEx does try to set the modification time, but it does NO error checking on it. This means if setting modification time fails internally in CopyFileEx (e.g. with access denied), latter will still returns successful!

So if modification time is important for your scenario (it is for my synchronization program), you have to explicitly call SetFileTime() and check it's return value to be sure.

你应该使用 SetFileTime()自己更新复制文件的时间戳,以确保将它们设置为您想要的设置。 MSDN 上有一个例子:

Changing a File Time to the Current Time

#include <windows.h>

// SetFileToCurrentTime - sets last write time to current system time
// Return value - TRUE if successful, FALSE otherwise
// hFile - must be a valid file handle

BOOL SetFileToCurrentTime(HANDLE hFile)
{
FILETIME ft;
SYSTEMTIME st;
BOOL f;

GetSystemTime(&st); // Gets the current system time
SystemTimeToFileTime(&st, &ft); // Converts the current system time to file time format
f = SetFileTime(hFile, // Sets last-write time of the file
(LPFILETIME) NULL, // to the converted current system time
(LPFILETIME) NULL,
&ft);

return f;
}

关于c++ - 如何复制文件但触摸新拷贝上的时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26514244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com