boost::filesystem recursively getting size of each file

Viewed 7747

Why does this code throw an error when the argument is a directory?

Using boost::recursive_directory_iterator and using std::cout statements, I can see that it never prints a directory; only files. But, when I try to call boost::filesystem::file_size(), an error is thrown basically saying I'm trying to get the file size of a directory.

Error (argument was "/home"):

terminate called after throwing an instance of 'boost::filesystem::filesystem_error'
  what():  boost::filesystem::file_size: Operation not permitted: "/home/lost+found"
Aborted
#include <iostream>
#include <boost/filesystem.hpp>

namespace fs = boost::filesystem;

int main(int argc, char* argv[])
{
    if (argc != 2) return -1;

    const fs::path file{argv[1]};

    if (!fs::exists(file)) return -1;

    if (fs::is_regular_file(file))
        std::cout << file << "   [ " << fs::file_size(file) << " ]\n";

    else if (fs::is_directory(file))
        for (const fs::directory_entry& f : fs::recursive_directory_iterator{file})
            std::cout << f.path().filename() << "   [ " << fs::file_size(f.path()) << " ]\n";
}

Compiled with: g++ -Wall -Wextra -pedantic-errors -std=c++14 -lboost_system -lboost_filesystem -O2 -Os -s test3.cpp -o test3

2 Answers
Related