tags:

views:

123

answers:

4

I'm attempting to write a program in Linux using C++ that counts the number of files and folders in a user specified directory, but the more I read, the more confused I get. I'm new to C++ and to programming in general, and I understand that I have a big hurdle to vault at the start, but I'm not entirely sure where to start reading on this one. I've read a bit about forking processes and system calls, but if someone were to briefly outline the process I have to go through to achieve this, then I can do more in depth reading on the various functions myself.

+4  A: 

With C++ Boost.FileSystem gives you convenient tools to achieve what you want.

If you want to learn the basic C APIs, take a look at File System Interface in the GNU C library manual.

Georg Fritzsche
+3  A: 

If you really want to do it the Linux way, take a look at the opendir, readdir, and closedir system calls. There is an example here that is basically the program you are trying to write (it prints contents instead of counting them, though).

If I were you, I would stick with a higher-level library like Georg suggested.

Tim Yates
A: 

On *nix you can the C library functions opendir and readdir

Basically, call opendir() to get a handle to a directory. Iterate through the entries in that directory with readdir()

nos
A: 

The simplest and most cross-platform way to do this is with boost::filesystem. On UNIX (Linux, Mac OS X, Free BSD, etc.) there are a number of ways to do this. As have been pointed out, opendir, readdir, and closedir are possibilities. I should point out that, instead of using readdir, it is better to use readdir_r which is reentrant (meaning that it is safe to use concurrently from multiple different threads), whereas the ordinary readdir call is not reentrant (and therefore not guaranteed by the Single UNIX Specification / IEEE Std. 1003.1 a.k.a. POSIX to be threadsafe). Though these may not be the easiest to use and not appropriate for this particular task, for other actions that walk the filesystem, you might also be interested in nftw and ftw, which are particularly well suited to acting on subtrees of the filesystem.

Michael Aaron Safyan