nikhil
nikhil

Reputation: 9385

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.

Upvotes: 13

Views: 13874

Answers (2)

Anon Mail
Anon Mail

Reputation: 4770

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.

Upvotes: 1

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

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

Upvotes: 26

Related Questions