Thursday, 6 September 2012

How to recursively walk a folder in C++ / Boost

Walking a folder structure in most languages is typically achieved using a recursive function or loop of some kind (although this behaviour may be wrapped and hidden from the programmer) - for C++ this is not any different. However the walking isn't the problem, rather writing a platform generic (Unix/Linux/Windows) version has been a little tricky due to C++ having no standardised support for folder/directory handling across different platforms (of course file handling is standardised.).
Boost makes this simple using it's filesystem library iterators and a very simple loop construct of your choice.

Example

This example shows a recursive walk of a folder structure printing the full path of all folders and files found.
#include <boost/filesystem.hpp>
#include <iostream>

void main()
{
    boost::filesystem::path path = boost::filesystem::current_path();
    boost::filesystem::recursive_directory_iterator itr(path);
    while (itr != boost::filesystem::recursive_directory_iterator())
    {
        std::cout << itr->path().string() << std::endl;
        ++itr;
    }
}
  1. Firstly we assume you have built the Boost filesystem library and it and it's header are appropriately defined in your project e.g. link to the library and include the header file.
  2. Next you create the iterator recursive_directory_iterator. We have loaded our iterator example with the current working directory.
  3. Finally you loop until you run out of iterators.

References

http://www.boost.org/


4 comments:

  1. How do you tell boost to list the files in alpha order?
    ie:

    a1
    a2
    b
    b3
    xxxx

    etc

    ReplyDelete
    Replies
    1. I believe you can use the std::sort.

      So for example if you have a vertor path you could use the begin and end iterators to sort them.

      Something like this (not tested)

      std::vector < path > myfolders;
      // fill the vector with folders from where ever
      std::sort(myfolders.begin(), myfolders.end();

      look here:
      http://www.boost.org/doc/libs/1_47_0/libs/filesystem/v3/doc/tutorial.html#Using-path-decomposition

      Delete
  2. C language is a computer programming language.Very easy to learn and a strutured language. C language is a object oriented programming.
    C++ training in chennai|Unix training in Chennai | FITA Velachery Reviews

    ReplyDelete
  3. @Dhivya Shree Well C is not an object oriented language at all I am afraid. It is a procedural language. I assume this is a typo.

    https://en.wikipedia.org/wiki/C_(programming_language)

    ReplyDelete