Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
josuttis_nm_c20_the_complete_guide.pdf
Скачиваний:
48
Добавлен:
27.03.2023
Размер:
5.85 Mб
Скачать

11.7 Clocks in Detail

399

11.7.5 Dealing with the File Clock

The clock std::chrono::file_clock is the clock the filesystem library uses for timepoints of filesystem entries (files, directories, etc.). It is an implementation-specific clock type that reflects the resolution and range of time values of the filesystem.

For example, you can use the file clock to update the time of last access to a file as follows:

// touch file with path p (update last write access to file): std::filesystem::last_write_time(p,

std::chrono::file_clock::now());

You were also able to use the clock of filesystem entries in C++17 by using the type std::filesystem::file_time_type:

std::filesystem::last_write_time(p, std::filesystem::file_time_type::clock::now());

Since C++20, the filesystem type name file_time_type is defined as follows: namespace std::filesystem {

using file_time_type = chrono::time_point<chrono::file_clock>;

}

In C++17, you could only use an unspecified trivial-clock.

For timepoints of the filesystem, the type file_time is also defined now: namespace std::chrono {

template<typename Duration>

using file_time = time_point<file_clock, Duration>;

}

A type like file_seconds (as the other clocks have) is not defined.

The new definition of the file_time type now allows programmers to portably convert filesystem timepoints to system timepoints. For example, you can print the time when a passed file was accessed last as follows:

void printFileAccess(const std::filesystem::path& p)

{

std::cout << "\"" << p.string() << "\":\n";

auto tpFile = std::filesystem::last_write_time(p);

std::cout << std::format(" Last write access: {0:%F} {0:%X}\n", tpFile);

auto diff = std::chrono::file_clock::now() - tpFile;

auto diffSecs = std::chrono::round<std::chrono::seconds>(diff); std::cout << std::format(" It is {} old\n", diffSecs);

}

This code might output:

"chronoclocks.cpp":

Last write access: 2021-07-12 16:50:08

400

Chapter 11: Dates and Timezones for <chrono>

It is 18s old

If you were to use the default output operator of timepoints, which prints subseconds according to the granularity of the file clock:

std::cout << " Last write access: " << diffSecs << '\n';

the output might be as follows:

Last write access: 2021-07-12 16:50:08.3680536

To deal with the file access time as system or local time, you have to use a clock_cast<>() (which, internally, might call the static file_clock member functions to_sys() or to_utc()). For example:

auto tpFile = std::filesystem::last_write_time(p); auto tpSys = std::chrono::file_clock::to_sys(tpFile);

auto tpSys = std::chrono::clock_cast<std::chrono::system_clock>(tpFile);