Namespaces
Variants
Views
Actions

Difference between revisions of "Template:cpp/filesystem/time example"

From cppreference.com
m (GCC 9 has distinct type for file clock, without to_time_t)
(Update code to compliance with c++ 20 standard.)
Line 12: Line 12:
 
     std::ofstream(p.c_str()).put('a'); // create file
 
     std::ofstream(p.c_str()).put('a'); // create file
 
     auto ftime = fs::last_write_time(p);
 
     auto ftime = fs::last_write_time(p);
 
+
    // assuming system_clock for this demo
+
     std::time_t cftime = std::chrono::system_clock::to_time_t(
    // note: not true on MSVC or GCC 9; C++20 will allow portable output
+
        std::chrono::file_clock::to_sys(ftime));
     std::time_t cftime = decltype(ftime)::clock::to_time_t(ftime);
+
 
     std::cout << "File write time is " << std::asctime(std::localtime(&cftime)) << '\n';
 
     std::cout << "File write time is " << std::asctime(std::localtime(&cftime)) << '\n';
 
+
 
     fs::last_write_time(p, ftime + 1h); // move file write time 1 hour to the future
 
     fs::last_write_time(p, ftime + 1h); // move file write time 1 hour to the future
 
     ftime = fs::last_write_time(p); // read back from the filesystem
 
     ftime = fs::last_write_time(p); // read back from the filesystem
 
+
     cftime = decltype(ftime)::clock::to_time_t(ftime);
+
     cftime = std::chrono::system_clock::to_time_t(
 +
        std::chrono::file_clock::to_sys(ftime));
 
     std::cout << "File write time is " << std::asctime(std::localtime(&cftime)) << '\n';
 
     std::cout << "File write time is " << std::asctime(std::localtime(&cftime)) << '\n';
 
     fs::remove(p);
 
     fs::remove(p);

Revision as of 09:01, 9 May 2021

#include <iostream>
#include <chrono>
#include <iomanip>
#include <fstream>
#include <filesystem>
namespace fs = std::filesystem;
using namespace std::chrono_literals;
int main()
{
    fs::path p = fs::current_path() / "example.bin";
    std::ofstream(p.c_str()).put('a'); // create file
    auto ftime = fs::last_write_time(p);
 
    std::time_t cftime = std::chrono::system_clock::to_time_t(
        std::chrono::file_clock::to_sys(ftime));
    std::cout << "File write time is " << std::asctime(std::localtime(&cftime)) << '\n';
 
    fs::last_write_time(p, ftime + 1h); // move file write time 1 hour to the future
    ftime = fs::last_write_time(p); // read back from the filesystem
 
    cftime = std::chrono::system_clock::to_time_t(
        std::chrono::file_clock::to_sys(ftime));
    std::cout << "File write time is " << std::asctime(std::localtime(&cftime)) << '\n';
    fs::remove(p);
}

Possible output:

File write time is Tue Mar 31 19:47:04 2015
 
File write time is Tue Mar 31 20:47:04 2015