Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

Learning Poco: List Directories Recursively

5.00/5 (1 vote)
14 Sep 2011CC (ASA 3U) 19K  
A simple utility program for listing directories recursively

In this tutorial, we will write a simple utility program for listing directories recursively. Poco provides DirectoryIterator to iterate over all the items contained in a directory. We will also make use of DateTimeFormatter to format the last-modified timestamp in our local time zone instead of the default UTC. This utility mimics the behavior of ls -all.

The Poco here stands for the POCO C++ libraries and is not to be confused with Plain Old CLR Object.

Create a file named rec_dir.cc with the following code:

C++
#include <Poco/DirectoryIterator.h>
#include <Poco/DateTimeFormatter.h>
#include <Poco/LocalDateTime.h>
#include <iostream>
#include <string>

using namespace Poco;
using namespace std;

void rec_dir(const string & path)
{
  DirectoryIterator end;
  for (DirectoryIterator it(path); it != end; ++it)
  {
    cout << (it->isDirectory() ? "d" : "-");
    cout << (it->canRead()     ? "r" : "-");
    cout << (it->canWrite()    ? "w" : "-");
    cout << (it->canExecute()  ? "x" : "-");
    cout << "\t";

    cout << it->getSize() << "\t";

    LocalDateTime lastModified(it->getLastModified());
    cout << DateTimeFormatter::format
    (lastModified, "%Y-%m-%d %H:%M") << "\t";

    cout << it->path() << (it->isDirectory() ? 
    "/" : it->canExecute() ? "*" : "") << endl;

    if (it->isDirectory())
    {
      rec_dir(it->path());
    }
  }
}

int main(int argc, char **argv)
{
  rec_dir(argc > 1 ? argv[1] : ".");
  return 0;
}

Compile it and run:

$ g++ -o rec_dir rec_dir.cc -lPocoFoundation
$ ./rec_dir
-rwx        14223   2011-09-14 13:34        rec_dir*
drwx        4096    2011-09-14 12:52        testdir/
drwx        4096    2011-09-14 12:52        testdir/dir/
-rw-        941     2011-09-14 13:24        rec_dir.cc
-rw-        0       2011-09-14 12:43        somefile

You may also try ./rec_dir .. or ./rec_dir ~. It’s fun! :–)

The code is simple enough but these classes provided by Poco are powerful. You may check out DirectoryIterator and File for information about other usage.

Related Articles

License

This article, along with any associated source code and files, is licensed under The Creative Commons Attribution-Share Alike 3.0 Unported License