C++17 includes a new and portable API for working with filesystems (<filesystem>
).
My program unpacks an archive. This archive contains files, directories and creatation time for each file. With the new API I have a portable solotution for creating directories (std::filesystem::create_directories
), and I am using std::ofstream
for creating files.
Can I use the new API for setting file createtion (or modification) time?
EDIT: Time, who providing by archive - it is seconds, start at 1970.01.01 00:00:00(UNIX Epoch time)
The answer to your question is... complicated. Because C++ gotta be C++.
In the most technical sense, the answer is yes: std::filesystem::last_write_time
can be used to set the last time of writing for the file.
The reason why the answer is not true in a more realistic sense is because last_write_time
takes a std::filesystem::file_time_type
as its time. And that's problematic.
See, the epoch for this time point (what constitutes 0 time) is... implementation-defined. It might be UNIX time (Zero is Jan 1, 1970 at 00:00:00). Or it might be something else.
Because it is implementation-defined, there is no way to portably turn a count of seconds/minutes/days/etc relative to some known epoch (like, for example, the time in your archive) into a std::filesystem::file_time_type
, simply because you don't know how to speak file_time_type
. The only thing you can really do is use existing file_time_type
s values and adjust them by any arbitrary count of time (or set it to the current time via file_time_type::clock::now()
). But you can't set a file's time to some known, absolute date/time.
C++20 fortunately plugs this hole. system_clock
will be required to run on UNIX time, and file_time_type
will be required to be able to be std::chrono::clock_cast
ed from/to any type that can be converted to the system_clock
time.
But until then, last_write_time
is not nearly as useful as it ought to be...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With