How to convert std::filesystem::file_time_type to time_t?

后端 未结 2 1352
清歌不尽
清歌不尽 2020-12-18 06:24

I wrote a solution for windows using MSVC2015 where the follow code converts the std::filesystem::last_write_time result time_t:

time_t ftime = std::file_tim         


        
2条回答
  •  悲哀的现实
    2020-12-18 07:13

    As already said, there is no perfect way to do that in C++17. Depending on the actual use-case it might be good enough to use a portable approximation. Based on my answer to "How to convert std::filesystem::file_time_type to a string using GCC 9", I want to suggest the helper function used there:

    template 
    std::time_t to_time_t(TP tp)
    {
        using namespace std::chrono;
        auto sctp = time_point_cast(tp - TP::clock::now()
                  + system_clock::now());
        return system_clock::to_time_t(sctp);
    }
    

    Be aware, that it uses a call to now() on each clock, so it is not an exact, round-trip-guaranteed solution, but it might be usable for you, until the gap in the library is closed. It is based on the fact that difference between time points of the same clock is easy and there is an operator+ for duration and time_point of different sources.

    For ways to lower the risk of a relevant error even more, I want to point to the conversion between C++11 clocks where some statistical analysis was made with ideas to mitigate possible errors, but when acceptable, I just use the code above.

提交回复
热议问题