Created
December 11, 2016 04:34
-
-
Save EricWF/e4882930e701740d7492f9b1117cb232 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <unistd.h> | |
| #include <sys/stat.h> | |
| #include <sys/statvfs.h> | |
| #include <fcntl.h> /* values for fchmodat */ | |
| #include <limits> | |
| #include <ctime> | |
| #include <cassert> | |
| #include <fstream> | |
| using TimeSpec = struct ::timespec; | |
| const int MaxNanoseconds = 100'000'000; | |
| TimeSpec const MaxTS = {std::numeric_limits<std::time_t>::max(), MaxNanoseconds - 1}; | |
| TimeSpec const MinTS = {std::numeric_limits<std::time_t>::min(), 0}; | |
| bool operator==(TimeSpec const& L, TimeSpec const& R) { | |
| return L.tv_sec == R.tv_sec && L.tv_nsec == R.tv_nsec; | |
| } | |
| bool set_last_write_time(const char* file, TimeSpec const& TS) { | |
| TimeSpec tbuf[2]; | |
| tbuf[0].tv_sec = 0; | |
| tbuf[0].tv_nsec = UTIME_OMIT; | |
| tbuf[1] = TS; | |
| return (::utimensat(AT_FDCWD, file, tbuf, 0) != -1); | |
| } | |
| TimeSpec get_last_write_time(const char* file) { | |
| struct ::stat st; | |
| int exit_code = ::stat(file, &st); | |
| assert(exit_code == 0); | |
| return st.st_mtim; | |
| } | |
| int main() { | |
| const char* filename = "/tmp/foo"; | |
| std::ofstream out(filename); | |
| out.close(); | |
| assert(set_last_write_time(filename, MaxTS)); | |
| assert(get_last_write_time(filename) == MaxTS); | |
| assert(set_last_write_time(filename, MinTS)); | |
| assert(get_last_write_time(filename) == MinTS); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment