Last active
March 6, 2023 12:48
-
-
Save bitkorn/8af7f39783d5578131e9d1981a0daeac to your computer and use it in GitHub Desktop.
scan a folder recursive and write the filenames with his size to a CSV file
This file contains 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 <iostream> | |
#include <filesystem> | |
#include <string> | |
#include <fstream> | |
namespace fs = std::filesystem; | |
using std::cout; | |
const std::string outFilePath = "/home/allapow/Downloads/fileAudit.csv"; | |
int main(int argc, char *argv[]) { | |
if (argc != 2) { | |
fprintf(stderr, "Usage: fileAudit directory\n"); | |
return (1); | |
} | |
cout << "working directory: " << fs::current_path() << "\n"; | |
cout << " scan directory: " << argv[1] << "\n"; | |
std::string path, outFilename(outFilePath); | |
std::fstream outfile; | |
fs::path scannPath(argv[1]); | |
try { | |
path = fs::canonical(scannPath); | |
} catch (std::exception &ex) { | |
cout << "Path does not exist: " << scannPath << "\nthrew exception:\n" << ex.what() << "\n"; | |
return (1); | |
} | |
cout << "scan path (canonical): " << path << "\n"; | |
outfile.open(outFilename, std::ios_base::out); | |
if (!outfile.is_open()) { | |
cout << "failed to open " << outFilename << '\n'; | |
return (1); | |
} | |
outfile << R"("bytes";"filename")" << std::endl; | |
// Iterate over the `std::filesystem::directory_entry` elements explicitly | |
for (const fs::directory_entry &dir_entry: fs::recursive_directory_iterator(path)) { | |
if (!fs::is_directory(dir_entry)) { | |
outfile << "\"" << fs::file_size(dir_entry.path()) << "\";" << dir_entry.path() << std::endl; | |
} | |
} | |
outfile.close(); | |
return 0; | |
} | |
void unusedStuff(fs::path *scannPath) { | |
/** | |
* Iterate with recursive_directory_iterator | |
*/ | |
fs::recursive_directory_iterator di(*scannPath), ende; | |
while (di != ende) { | |
for (int i = 0; i < di.depth(); ++i) { | |
std::cout << " | "; | |
} | |
std::cout << " |-- " << di->path().filename().string() << "\n"; | |
++di; | |
} | |
std::cout << "-----------------------------\n"; | |
/** | |
* Iterate over the `std::filesystem::directory_entry` elements using `auto` | |
*/ | |
for (auto const &dir_entry: fs::recursive_directory_iterator("/my/path")) { | |
std::cout << dir_entry << '\n'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment