LearnFrenzy
Sign in Take a free test

File Handling (fstream) · File Handling Programs · Question 9

Organise files by extension with std::filesystem Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

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;
}

Output Verified by compiling and running

jpg/ photo1.jpg photo2.jpg
other/ README
pdf/ cv.pdf
txt/ notes.txt todo.txt

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links