Namespaces
Variants
Views
Actions

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

From cppreference.com
m (Example: wrap up some code repetition into a closure.)
(changed to use filly qualified names so that they are clickable links)
Line 5: Line 5:
 
#include <fstream>
 
#include <fstream>
 
#include <filesystem>
 
#include <filesystem>
namespace fs = std::filesystem;
+
 
 
using namespace std::chrono_literals;
 
using namespace std::chrono_literals;
 
int main()
 
int main()
 
{
 
{
     fs::path p = fs::temp_directory_path() / "example.bin";
+
     auto p = std::filesystem::temp_directory_path() / "example.bin";
 
     std::ofstream(p.c_str()).put('a'); // create file
 
     std::ofstream(p.c_str()).put('a'); // create file
  
     auto print_last_write_time = [](fs::file_time_type const& ftime) {
+
     auto print_last_write_time = [](std::filesystem::file_time_type const& ftime) {
 
         std::time_t cftime = std::chrono::system_clock::to_time_t(
 
         std::time_t cftime = std::chrono::system_clock::to_time_t(
 
             std::chrono::file_clock::to_sys(ftime));
 
             std::chrono::file_clock::to_sys(ftime));
Line 18: Line 18:
 
     };
 
     };
  
     fs::file_time_type ftime = fs::last_write_time(p);
+
     auto ftime = std::filesystem::last_write_time(p);
 
     print_last_write_time(ftime);
 
     print_last_write_time(ftime);
  
     fs::last_write_time(p, ftime + 1h); // move file write time 1 hour to the future
+
     std::filesystem::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 = std::filesystem::last_write_time(p); // read back from the filesystem
 
     print_last_write_time(ftime);
 
     print_last_write_time(ftime);
  
     fs::remove(p);
+
     std::filesystem::remove(p);
 
}
 
}
 
|p=true
 
|p=true

Revision as of 06:09, 23 June 2021

#include <iostream>
#include <chrono>
#include <iomanip>
#include <fstream>
#include <filesystem>
 
using namespace std::chrono_literals;
int main()
{
    auto p = std::filesystem::temp_directory_path() / "example.bin";
    std::ofstream(p.c_str()).put('a'); // create file
 
    auto print_last_write_time = [](std::filesystem::file_time_type const& ftime) {
        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));
    };
 
    auto ftime = std::filesystem::last_write_time(p);
    print_last_write_time(ftime);
 
    std::filesystem::last_write_time(p, ftime + 1h); // move file write time 1 hour to the future
    ftime = std::filesystem::last_write_time(p); // read back from the filesystem
    print_last_write_time(ftime);
 
    std::filesystem::remove(p);
}

Possible output:

File write time is Sun May  9 23:29:58 2021
File write time is Mon May 10 00:29:58 2021