Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a Boost FileSystem3 iterator to a const char*

Tags:

c++

casting

boost

I'm looping over some file in a directory using Boost FileSystem 3 and I need to cast the filename to a char* for another lib, Unfortunately my C++ foo is lacking, can anyone help ?

  int main(int argc, char* argv[])
    {
      path p (argv[1]);   // p reads clearer than argv[1] in the following code

      try
      {
        if (exists(p))    // does p actually exist?
        {
          if (is_regular_file(p))        // is p a regular file?   
            cout << p << " size is " << file_size(p) << '\n';

          else if (is_directory(p))      // is p a directory?
          {
            cout << p << " is a directory containing:\n";

            typedef vector<path> vec;             // store paths,
            vec v;                                // so we can sort them later

            copy(directory_iterator(p), directory_iterator(), back_inserter(v));

            sort(v.begin(), v.end());             // sort, since directory iteration
                                                  // is not ordered on some file systems

            for (vec::const_iterator it (v.begin()); it != v.end(); ++it)
            {
              cout << "   " << *it << '\n';
       /****************** stuck here **************************/
      // I need to cast *it to a const char* filename 
       /****************** stuck here **************************/
            }
          }

          else
            cout << p << " exists, but is neither a regular file nor a directory\n";
        }
        else
          cout << p << " does not exist\n";
      }

      catch (const filesystem_error& ex)
      {
        cout << ex.what() << '\n';
      }

      return 0;
    }
like image 275
macarthy Avatar asked Jul 26 '11 06:07

macarthy


1 Answers

The expression*it returns an object of type path, so you've to this:

const std::string & s = (*it).string(); 
const char *str = s.c_str(); //this is what you want

Or maybe you want to use other conversion functions, as listed below:

const std::string & string() const;
std::string native_file_string() const;
std::string native_directory_string() const;

Choose whichever you want to use. Read the documentation first as to what each of them returns:

  • boost/filesystem/path.hpp
like image 66
Nawaz Avatar answered Sep 20 '22 02:09

Nawaz