How to iterate directory streams in Linux
posted on: 2010-04-25 11:55:29
I decided to add this tutorial as I have seen many people asking questions on iterate directories in linux. I will also combine this with how to implement the wxTree control. The wxWidgets framework is a multi platform and supported on Linux, Windows and Mac.
The solution that is easiest to use is the dirent header from the POSIX library. The POSIX library has been implemented on most common platforms. It contains functions for opening, reading and closing directory streams.
#include <dirent.h>
In the source code example accompanying this article. I have written a recursive function that utilizes dirent to iterate a given directory and build composite relationship of directories and files (composite as in the design pattern).
But here is a simplified, non recursive, fundamental skeleton of what is going on.
DIR *dp;
struct dirent *ep;
std::string path = ../somewhere/..;
dp = opendir (path.c_str());
while ((ep = readdir (dp)) != NULL)
{
std::cout << ep->d_name << std::endl;
}
(void) closedir (dp);
In the source code example populate a class of directory information and use this populate a wxWidget wxTreeCtrl class. I am a supporter of the wxWidgets libraries and I would encourage anyone considering developing any kind of application requiring user interface to use it. The wxWidget libraries are available on Linux, Windows, Mac and require minor changes to port from one OS to another.
The following .tar.gz contains the source and the compiled binary. I will discuss other aspects this example in future posts, so stay tuned. If you haven't already follow me on twitter.













