Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a boost::filesystem::directory_iterator to a const char *

I want to iterate over all the files in a directory and print their contents. Boost handles the iteration part very nicely but I have no idea how to conver that into a const char *.

boost::filesystem::directory_iterator path_it(path);
    boost::filesystem::directory_iterator end_it;
    while(path_it != end_it){
      std::cout << *path_it << std::endl;

      // Convert this to a c_string
      std::ifstream infile(*path_it);
    }

I tried to read this documentation but couldn't find anything like string or c_str(). I'm new to both C++ and boost and was hoping to find some javadoc like documentation which would basically tell me what the members were and what functions were availabe instead of dumping the source code.

Sorry for the rant but could someone tell me how to convert *path_it into a c string.

like image 777
nikhil Avatar asked May 01 '13 12:05

nikhil


2 Answers

When you dereference the iterator it returns a directory_entry:

const directory_entry& entry = *path_it;

You can use this along with operator<< and ostream, as you've discovered:

std::cout << entry << std::endl;

You could create a string using ostringstream:

std::ostringstream oss;

oss << entry;

std::string path = oss.str();

Alternatively you can access the path as a string directly from directory_entry:

std::string path = entry.path().string();
like image 193
Peter Wood Avatar answered Oct 21 '22 04:10

Peter Wood


After looking at the documentation I think you can do path_it->path().c_str() since a directory_iterator iterates over directory_entry which has a path() function which in turn has a c_str() function.

like image 37
Anon Mail Avatar answered Oct 21 '22 04:10

Anon Mail