0

I want to compare the file age of two files. I tried this:

auto ft1 = std::filesystem::last_write_time("file1");
auto ft2 = std::filesystem::last_write_time("file2");
if (ft1 < ft2)
  std::cout << "file1 is older than file2.";

Unfortunately sometimes the condition is true even if both file ages are equal. Converting to time_t helps:

auto ft1 = std::chrono::system_clock::to_time_t(std::filesystem::last_write_time("file1"));
auto ft2 = std::chrono::system_clock::to_time_t(std::filesystem::last_write_time("file2"));
if (ft1 < ft2)
  std::cout << "file1 is older than file2.";

This always works fine. Any ideas what's the problem with my first version?

  • 3
    The value returned by `std::filesystem::last_write_time` may be more precise than `time_t`. How did you verify that the times are supposed to be equal? – user17732522 Mar 04 '22 at 11:47
  • file1 was copied to file2 by std::filesystem::copy("file1", "file2);. That should not modify last_write_time. – Markus Donath Mar 04 '22 at 12:52
  • `the condition is true even if both file ages are equal.` How do you know they are equal? You just checked, and they are not. Why would you assume they are equal? || `was copied` `should not modify last_write_time` why? – KamilCuk Mar 04 '22 at 15:10
  • 1
    [`std::filesystem::copy`](https://en.cppreference.com/w/cpp/filesystem/copy) doesn't provide any guarantee that the 'last modified' time will be preserved in the copied file. Indeed, a quick test suggests that all timestamps associated with the copy are set to the time of the copy operation. If you require the timestamps to be the same use [`std::filesystem::last_write_time("file2", ft1)`](https://en.cppreference.com/w/cpp/filesystem/last_write_time). – G.M. Mar 04 '22 at 15:13
  • at my system std::filesystem::copy copies the file attributes too including last_write_time. But sometimes there is a difference of little milliseconds. The difference between last_write_time and time of the copy operation is many years in my example. I think it is an operating system issue. – Markus Donath Mar 05 '22 at 16:10

0 Answers0