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:
#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
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.