C++如何获取文件最近更改的时间戳

C++ how to get the recently changed timestamp of a file?

本文关键字:最近 时间戳 文件 何获取 获取 C++      更新时间:2023-10-16

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

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

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

例如

  • 重命名文件名的时间戳(到目前为止无法运行)

  • 修改文件的时间戳(mctime提供了这一点,但我会预先准备一个单向解决方案)

提前感谢。

如果您在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

我使用Boost的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();

参考文献:

  • put_time
  • time_t
  • ostringstream

编辑:

由于操作系统在重命名时不会更新文件的时间戳,因此您将不得不不幸地开始侦听事件。这篇SO文章提供了一些很好的信息,介绍如何与C++挂钩。

C++端有ReadDirectoryChangesW,它允许您将回调作为LPOVERLAPPED_COMPLETION_ROUTINE传递。就像许多特定于操作系统的代码一样,它可能很难很快跟上。

至于";触摸";在重命名文件以便更新时间戳时,可以将其复制到自身。参见CopyFile

如果你不反对编写托管C++代码,那么FileSystemWatercher的重命名事件