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

nikhil picture nikhil · May 1, 2013 · Viewed 12.8k times · Source

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.

Answer

Peter Wood picture Peter Wood · May 1, 2013

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();