Debian Codegraph @

gulrak-filesystem/examples/dir.cpp

raw
1 #include <chrono>
2 #include <iomanip>
3 #include <iostream>
4 #include <string>
5
6 #if defined(__cplusplus) && __cplusplus >= 201703L && defined(__has_include)
7 #if __has_include(<filesystem>)
8 #define GHC_USE_STD_FS
9 #include <filesystem>
10 namespace fs = std::filesystem;
11 #endif
12 #endif
13 #ifndef GHC_USE_STD_FS
14 #include <ghc/filesystem.hpp>
15 namespace fs = ghc::filesystem;
16 #endif
17
18 template <typename TP>
19 std::time_t to_time_t(TP tp)
20 {
21 // Based on trick from: Nico Josuttis, C++17 - The Complete Guide
22 std::chrono::system_clock::duration dt = std::chrono::duration_cast<std::chrono::system_clock::duration>(tp - TP::clock::now());
23 return std::chrono::system_clock::to_time_t(std::chrono::system_clock::now() + dt);
24 }
25
26 static std::string perm_to_str(fs::perms prms)
27 {
28 std::string result;
29 result.reserve(9);
30 for (int i = 0; i < 9; ++i) {
31 result = ((static_cast<int>(prms) & (1 << i)) ? "xwrxwrxwr"[i] : '-') + result;
32 }
33 return result;
34 }
35
36 int main(int argc, char* argv[])
37 {
38 #ifdef GHC_FILESYSTEM_VERSION
39 fs::u8arguments u8guard(argc, argv);
40 if (!u8guard.valid()) {
41 std::cerr << "Invalid character encoding, UTF-8 based encoding needed." << std::endl;
42 std::exit(EXIT_FAILURE);
43 }
44 #endif
45 if (argc > 2) {
46 std::cerr << "USAGE: dir <path>" << std::endl;
47 exit(1);
48 }
49 fs::path dir{"."};
50 if (argc == 2) {
51 dir = fs::u8path(argv[1]);
52 }
53 for (auto de : fs::directory_iterator(dir)) {
54 auto ft = to_time_t(de.last_write_time());
55 auto ftm = *std::localtime(&ft);
56 std::cout << (de.is_directory() ? "d" : "-") << perm_to_str(de.symlink_status().permissions()) << " " << std::setw(8) << (de.is_directory() ? "-" : std::to_string(de.file_size())) << " " << std::put_time(&ftm, "%Y-%m-%d %H:%M:%S") << " "
57 << de.path().filename().string() << std::endl;
58 }
59 return 0;
60 }