0

Below function read directory and insert files name (by push_back()) into vector

#include <dirent.h>

void open(string path){

    DIR* dir;
    dirent *pdir;

    dir = opendir(path.c_str());
    while (pdir = readdir(dir)){
        vectorForResults.push_back(pdir->d_name);
    }
}

Question: How can I check size of each file (from current directiory) using boots library?

I found method described on http://en.highscore.de/cpp/boost/filesystem.html

It's e.g.:

boost::filesystem::path p("C:\\Windows\\win.ini"); 
std::cout << boost::filesystem::file_size(p) << std::endl; 

Could someone please help how to implement boost it in my open() function? Especially how to assign current directory path name into variable p and then iterate through files names.

Lord Zsolt
  • 6,492
  • 9
  • 46
  • 76
gen_next
  • 97
  • 1
  • 12
  • 2
    If only there were some kind of [reference](http://www.boost.org/doc/libs/1_56_0/libs/filesystem/doc/reference.html)... – user657267 Oct 19 '14 at 11:43
  • boost::filesystem::path p(path.c_str()) but without success ... – gen_next Oct 19 '14 at 11:43
  • possible duplicate of [Printing off\_t file size from dirent struct](http://stackoverflow.com/questions/20528616/printing-off-t-file-size-from-dirent-struct) – Jongware Oct 19 '14 at 11:47
  • You might not be using `pdir` correctly. It may point to static buffer so make sure you are taking a copy of what it's pointing to. If `vectorForResults` is storing pointers then you are in trouble. – M.M Oct 19 '14 at 12:09

2 Answers2

1

Does this help?

Live On Coliru

#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>
#include <iostream>

namespace fs = boost::filesystem;

int main()
{
    for(auto& f : boost::make_iterator_range(fs::directory_iterator("."), {}))
    {
        if (fs::is_regular(f))
            std::cout << fs::file_size(f) << "\t" << f << "\n";
    }
}

Note that "." is the current directory

sehe
  • 374,641
  • 47
  • 450
  • 633
  • It works when I changed first line to: for(auto& f : boost::make_iterator_range(fs::directory_iterator("."))) Big thanks @sehe! – gen_next Oct 19 '14 at 21:45
0
#include <dirent.h>

void open(std::string path){

    DIR* dir;
    dirent *pdir;

    dir = opendir(path.c_str());
    while (pdir = readdir(dir)){
        std::string p = path + "/" + pdir->d_name;
        vectorForResults.push_back(pdir->d_name);
        std::cout << boost::filesystem::file_size(p) << std::endl;
    }
}

I think it's what you were looking for. You don't need to create a boost::filesystem::path object.

Or you can use the C function stat: http://linux.die.net/man/2/stat

Marchah
  • 160
  • 14