samedi 14 septembre 2013

How to read / list directory and its subdirectories with C++ ?

A simple way to read or list files or directories is to use Dirent Lib which can be downloaded from here and installed in the same way as it was shown for OpenCV Lib here (if you are using Microsoft Visual C++ Express) or here (if you are using Visual Studia 2010)
Actually I need this Lib to read an image database where I have many directories and each one have a different number of images. So I can't use a constant number to read every directory, that's why I have turned to use Dirent Lib.
Here I give an example to show how to use  it:

# include <dirent.h> 
#include "stdafx.h" 
#include <highgui.h>

void main()
{
  DIR *pDIR;
  struct dirent *entry;
  if( pDIR = opendir(ClassPath.c_str()) )
    {
         while(entry = readdir(pDIR))
            {
                 if( strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0 )
                  

                          // Specify image path
                           string ImgPath = stra  + "/" + entry->d_name ;
                          //Load the image
                           IplImage* Src = cvLoadImage(ImgPath.c_str());

                          // Then here ...You can add any processing you want for that image/file !
                           Blablabliblou ......
                        //Free Memory
                         cvReleaseImage(&Src);
                    
             }                   
           closedir(pDIR);
      }

 }