I'm trying to format the modification time of a file as a string (UTC). The following code compiles with GCC 8, but not GCC 9.
#include <chrono>
#include <filesystem>
#include <iomanip>
#include <iostream>
#include <sstream>
namespace fs = std::filesystem;
int main() {
fs::file_time_type file_time = fs::last_write_time(__FILE__);
std::time_t tt = decltype(file_time)::clock::to_time_t(file_time);
std::tm *gmt = std::gmtime(&tt);
std::stringstream buffer;
buffer << std::put_time(gmt, "%A, %d %B %Y %H:%M");
std::string formattedFileTime = buffer.str();
std::cout << formattedFileTime << '\n';
}
I tried both decltype(file_time)::clock
and std::chrono::file_clock
, using both C++17 and C++ 20, but neither of them worked.
$ g++-9 -std=c++2a -Wall -Wextra -lstdc++fs file_time_type.cpp
file_time_type.cpp: In function ‘int main()’:
file_time_type.cpp:12:50: error: ‘to_time_t’ is not a member of ‘std::chrono::time_point<std::filesystem::__file_clock>::clock’ {aka ‘std::filesystem::__file_clock’}
12 | std::time_t tt = decltype(file_time)::clock::to_time_t(file_time);
| ^~~~~~~~~
The example on https://en.cppreference.com/w/cpp/filesystem/file_time_type mentions that it doesn't work on GCC 9, because C++20 will allow portable output, but I have no idea how to get it working. Shouldn't it work with GCC 9 if I just not use C++20?
I would prefer a C++17 solution with GCC 9, if possible.
time_t
– Cyr