Given a folder of mixed files, create a subfolder per extension (pdf, jpg, txt, …) and move each file into it with std::filesystem::rename; print a sorted summary of the folders.
Solution
main.cpp
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
namespace fs = std::filesystem;
int main() {
fs::path dir = fs::temp_directory_path() / "lf_downloads";
fs::remove_all(dir);
fs::create_directory(dir);
for (std::string f : {"notes.txt", "cv.pdf", "photo1.jpg", "photo2.jpg", "todo.txt", "README"}) std::ofstream(dir / f) << f;
std::vector<fs::path> files;
for (const auto& e : fs::directory_iterator(dir)) if (e.is_regular_file()) files.push_back(e.path());
for (const auto& f : files) {
std::string ext = f.has_extension() ? f.extension().string().substr(1) : "other";
fs::create_directories(dir / ext);
fs::rename(f, dir / ext / f.filename());
}
std::map<std::string, std::vector<std::string>> summary;
for (const auto& e : fs::recursive_directory_iterator(dir))
if (e.is_regular_file()) summary[e.path().parent_path().filename().string()].push_back(e.path().filename().string());
for (auto& [folder, names] : summary) {
std::sort(names.begin(), names.end());
std::cout << folder << '/';
for (const auto& n : names) std::cout << ' ' << n;
std::cout << '\n';
}
fs::remove_all(dir);
return 0;
}
The file list is collected before moving anything, because changing a directory while iterating it is unsafe. Results are sorted since directory order is unspecified.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!