Ahmed A
Ahmed A

Reputation: 3652

C++ directory_iterator

It's been quite a while since I worked with C++, please pardon me for my newbie questions.

I wrote the following code to get a listing of the contents of a directory, which is working fine:

for (directory_iterator end, dir("./");
     dir != end; dir++) {
    std::cout << *dir << std::endl;
}

What does "*dir" return, a pointer a "char array", a pointer to a "string" object, or a pointer to "path" object?

I want to pass "*dir" (if it ends with .cpp) to another function(), which will act on it (asynchronously) at a later time. I guessing I need to make a copy of "*dir". I wrote the following code:

path *_path;
for (directory_iterator end, dir("./");
     dir != end; dir++) {
    _path = new path(*dir);
    if (_path->extension() == ".cpp") {
        function1(_path);    // function1() will free _path
    } else
        free(_path);
}

Thank you, Ahmed.

Upvotes: 4

Views: 6391

Answers (1)

J. Calleja
J. Calleja

Reputation: 4905

From the documentation of boost::directory_iterator:

The result of operator* on an end iterator is not defined. For any other iterator value a const directory_entry& is returned.

Regarding the function call, I think the easiest way is:

using namespace boost::filesystem;

for (directory_iterator end, dir("./"); dir != end; dir++) {
  const boost::filesystem::path &this_path = dir->path();
  if (this_path.extension() == ".cpp") {
    function1(this_path); // Nothing to free
  } 
}

Where the function1 method can be declared as:

void function1(const boost::filesystem::path this_path);

Upvotes: 4

Related Questions