1

我想确定 Windows 上文件最近更改的时间戳。

是的,我用过 stat 函数和 st_atime、st_mtime、st_ctime。但是,Windows 不会为特定文件更新这些时间戳。(我不想改变这种行为,因为这将在稍后特定于客户)。

那么,如何确定文件最近更改的时间戳?

例如

  • 重命名文件名的时间戳(目前无法正常工作

  • 修改文件的时间戳(mctime 提供了这个,但我会推荐一种单向解决方案)

提前致谢。

4

2 回答 2

1

如果您在 Windows 上,请使用GetFileTime( https://msdn.microsoft.com/en-us/library/windows/desktop/ms724320(v=vs.85).aspx ) 通过CreateFile ( https:// /msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx )。

为此,我真的建议您阅读文章“检索上次写入时间”: https ://msdn.microsoft.com/en-us/library/windows/desktop/ms724926(v=vs.85).aspx

评论后编辑

在您的应用程序的包含部分:

#include <string>
#include <sstream>
#include <iostream>

GetLastWriteTime来自链接的方法中,而不是StringCchPrintf添加:

// Build a string showing the date and time.
std::stringstream ss;
ss << stLocal.wYear << "-" << stLocal.wMonth << "-" << stLocal.wDay << " " << stLocal.wHour << ":" << stLocal.wMinute ;
std::string timeString = ss.str();
std::cout << timeString;

请阅读以下文档:http ://www.cprogramming.com/tutorial/c++-iostreams.html ,然后参考http://en.cppreference.com/w/cpp/io/basic_stringstream

于 2017-02-03T12:16:30.190 回答
1

我使用 Boost's 取得了很大的成功filesystem::last_write_time(path),尽管我的 Windows 经验告诉我,如果您在短时间内对文件进行大量写入,那么返回时间戳的分辨率不足以区分您是否'在每次写入后询问时间戳

你可以像这样使用它:

boost::filesystem::path filePath = "Path/To/My/File.txt"
std::time_t writeTime = boost::filesystem::last_write_time(filePath);
std::ostringstream ss;
ss << std::put_time(&writeTime, "%c %Z");
std::string timeString = ss.str();

参考:

编辑:

由于操作系统不会在重命名时更新文件的时间戳,因此不幸的是,您将不得不开始监听事件。这篇 SO 帖子有一些关于从 C++ 中挂钩的好信息。

C++ 方面有ReadDirectoryChangesW,它允许您将回调作为 a 传递,LPOVERLAPPED_COMPLETION_ROUTINE就像许多特定于操作系统的代码一样,它很难很快地遵循。

至于在重命名时“触摸”文件以更新时间戳,您可以将其复制到自身。看CopyFile

如果您不反对编写托管 C++ 代码,则可以使用 FileSystemWatercher 的重命名事件

于 2017-02-03T13:06:38.147 回答