/* listdir_verbose
 *
 * Small example application which lists all files in a given directory and
 * (optionally) recursively the content of its subdirectories.
 *
 * It demonstrates the use of the ostream_iterator with the
 * filesystem::file_iterator.
 */

/* Note: Do not include config.h in your own programs. See README. */
#ifdef HAVE_CONFIG_H
#	include <config.h>
#endif

#include <fs++/file_iterator.h>
#include <iostream>
#include <iterator>
#include <string>

using namespace std ;
using filesystem::file_iterator ;
using filesystem::file_t ;
using filesystem::isDirectory ;

int
main (int argc, char** argv)
	{
		if ((argc < 2) || (argc > 3))
			{
				cerr << "Usage: listdir_verbose [ -r ] /some/directory" << endl ;
				return -1 ;
			}

		bool recursive = false ;
		if (argc == 3)
			{
				if (string (argv[1]) == "-r")
					{
						recursive = true ;
					}
				else
					{
						cerr << "Bad argument: \"" << argv[1] << "\"" << endl ;
						return -2 ;
					}
			}

		string dir (argv[argc - 1]) ;
		file_iterator<> i (dir);

		// The file_iterator does not provide the top-level directory during
		// iterations, so we output it by hand:
		cout << i.currentDirectory () << endl ;

		while (i != i.end ())
			{
				file_t cur_file = *i ;

				cout << (isDirectory (cur_file.getName ()) ? "[dir ] " : "[file] ") ;
				cout << cur_file << endl ;

				// The default behaviour of file_iterator is to descend into
				// subdirectories. But fortunately it provides a method to advance the
				// iterator by hand without descending into subdirectories:
				if (!recursive)
					{
						i.advance (false) ;
					}
				else
					{
						// behind the scenes, this calls in fact "advance (true)" ;-)
						i++ ;
					}

				// Or simply: "i.advance (recursive)" ;-)
			}

		return 0 ;
	}


syntax highlighted by Code2HTML, v. 0.9.1