Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

11.2. Traversing a Directory

Our next example traverses a directory tree. It starts as a hardcoded directory and then recursively displays all the files, subdirectories, and their contents in that directory. If you start this program in the root directory of a large filesystem or partition, the output may be quite lengthy. Let's first look at the code in Example 11-2:

Example 11-2. dirtraverse.cpp: Traversing a directory tree

#include <qapplication.h>
#include <qdir.h>
#include <qfileinfo.h>

void traverse( const QString& dirname );

void traverse( const QString& dirname )
{
  QDir dir( dirname );
  dir.setFilter( QDir::Dirs | QDir::Files | QDir::NoSymLinks );

  const QFileInfoList* fileinfolist = dir.entryInfoList();
  QFileInfoListIterator it( *fileinfolist );
  QFileInfo* fi;
  while( ( fi = it.current() ) ) {
    if( fi->fileName() == "." || fi->fileName() == ".."  ) {
      ++it;
      continue;
    }
    if( fi->isDir() && fi->isReadable() )
      traverse( fi->absFilePath() );
    else
      qDebug( "%s\n", fi->absFilePath().data() );
  
    ++it;
  }

  delete fileinfolist;
}

int main( int argc, char* argv[] )
{
  QApplication a( argc, argv );

  traverse( "/" ); // for Windows, use something like "C:\\"

  return 0;
}

					  


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint