Filesystem listing

Filesystem listing

You might have to go to project settings to ensure that your C++ version is set to C++17 or later.

Write a program that uses the std::filesystem library to list all files and directories in a specified directory. For each file, display its size. For directories, tag them as "Directory".

Hint

Answer

#include <iostream>
#include <filesystem>

int main() {
    std::string directoryPath;
    std::cout << "Enter the path to the directory: ";
    std::cin >> directoryPath;

    for (const auto& entry : std::filesystem::directory_iterator(directoryPath)) {
        auto path = entry.path();
        std::cout << "Name: " << path.filename().string() << std::endl;

        if (std::filesystem::is_directory(path)) {
            std::cout << "Type: Directory" << std::endl;
        } else if (std::filesystem::is_regular_file(path)) {
            std::cout << "Size: " << std::filesystem::file_size(path) << " bytes" << std::endl;
        } else {
            std::cout << "Type: Other" << std::endl;
        }

        std::cout << std::endl;
    }

    return 0;
}
Questions