c++windowsstd-filesystem

Does std::filesystem::last_write_time require a minimum Windows 10 version


I use std::filesystem::last_write_time which throws an exception on various Windows installations.

Minimal code example:

#include <fstream>
#include <iostream>
#include <filesystem>

int main()
{
    auto last_write_time = std::filesystem::temp_directory_path() / "last_write_time.txt";
    std::ofstream(last_write_time.c_str()) << "Hello, World!";

    try
    {
        auto ftime = std::filesystem::last_write_time(last_write_time);
        std::cout << ftime << std::endl;
    }
    catch (const std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }

    std::filesystem::remove(last_write_time);
}

My conclusion is that std::filesystem::last_write_time requires a minimum Windows10 version as std::chrono::current_zone does

VS2019 16.10 Release notes

VS 2019 16.10 Release notes screenshot snippet


Solution

  • std::filesystem::last_write_time doesn't require a minimum Windows version, but to convert the resulting file_time to sys_time needs the leap second database, and thus requires Windows 10 version 1809 or later. (In your minimal code example, it is std::cout << ftime that internally triggers a conversion to sys_time.)

    This is because MSVC STL implements the conversion from file_time to sys_time using two steps: first it converts file_time to utc_time (which is leap-second-aware); then it converts utc_time to sys_time (which is not leap-second-aware). The second step requires the leap second database in order to work correctly.

    You can work around this by implementing the conversion on your own, but be aware that:

    1. file_time and sys_time have different epochs.
    2. The result might be slightly incorrect if a leap second is inserted in the future.