Debian Codegraph @

gulrak-filesystem/examples/du.cpp

raw
1 #include <iostream>
2 #include <iomanip>
3 #include <chrono>
4
5 #if defined(__cplusplus) && __cplusplus >= 201703L && defined(__has_include)
6 #if __has_include(<filesystem>)
7 #define GHC_USE_STD_FS
8 #include <filesystem>
9 namespace fs = std::filesystem;
10 #endif
11 #endif
12 #ifndef GHC_USE_STD_FS
13 #include <ghc/filesystem.hpp>
14 namespace fs = ghc::filesystem;
15 #endif
16
17 int main(int argc, char* argv[])
18 {
19 #ifdef GHC_FILESYSTEM_VERSION
20 fs::u8arguments u8guard(argc, argv);
21 if(!u8guard.valid()) {
22 std::cerr << "Invalid character encoding, UTF-8 based encoding needed." << std::endl;
23 std::exit(EXIT_FAILURE);
24 }
25 #endif
26 if(argc > 2) {
27 std::cerr << "USAGE: du <path>" << std::endl;
28 exit(1);
29 }
30 fs::path dir{"."};
31 if(argc == 2) {
32 dir = fs::u8path(argv[1]);
33 }
34
35 uint64_t totalSize = 0;
36 int totalDirs = 0;
37 int totalFiles = 0;
38 int maxDepth = 0;
39
40 try {
41 auto rdi = fs::recursive_directory_iterator(dir);
42 for(auto de : rdi) {
43 if(rdi.depth() > maxDepth) {
44 maxDepth = rdi.depth();
45 }
46 if(de.is_regular_file()) {
47 totalSize += de.file_size();
48 ++totalFiles;
49 }
50 else if(de.is_directory()) {
51 ++totalDirs;
52 }
53 }
54 }
55 catch(fs::filesystem_error fe) {
56 std::cerr << "Error: " << fe.what() << std::endl;
57 exit(1);
58 }
59 std::cout << totalSize << " bytes in " << totalFiles << " files and " << totalDirs << " directories, maximum depth: " << maxDepth << std::endl;
60 return 0;
61 }