Search code examples
c++c++-chronoboost-filesystem

How to compare time_t and std::filesystem::file_time_type


I'm converting some code over from boost::filesystem to std::filesystem. Previous code used boost::filesystem::last_write_time() which returns a time_t so direct comparison to a time_t object I already held was trivial. By the way, this time_t I hold is read from file contents persisted long ago, so I'm stuck with using this "time since unix epoch" type.

std::filesystem::last_write_time returns a std::filesystem::file_time_type. Is there a portable way to convert a file_time_type to a time_t, or otherwise portably compare the two objects?

#include <ctime>
#include <filesystem>

std::time_t GetATimeInSecondsSince1970Epoch()
{
    return 1207609200;  // Some time in April 2008 (just an example!)
}

int main()
{
    const std::time_t time = GetATimeInSecondsSince1970Epoch();
    const auto lastWriteTime = std::filesystem::last_write_time("c:\\file.txt");

    // How to portably compare time and lastWriteTime?
}

EDIT: Please note that the sample code at cppreference.com for last_write_time states that it's assuming the clock is a std::chrono::system_clock which implements the to_time_t function. This assumption is not always going to be true and isn't on my platform (VS2017).


Solution

  • The very article you linked shows how to do this: through to_time_t member of the corresponding clock of the file_time_type.

    Copy-paste from your own link:

    auto ftime = fs::last_write_time(p);
    std::time_t cftime = decltype(ftime)::clock::to_time_t(ftime); 
    

    If your platform doesn't give you system_clock as a clock for file_time_type, than there would be no portable solution (until, at least, C++20 when file_time_type clock is standardized). Until than, you'd have to figure out what clock it actually is and than cast time appropriately through duration_cast and friends.