Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

Yet Another Useful Class for Listing Files

0.00/5 (No votes)
24 Sep 2012CPOL2 min read 6.6K   58  
A class for listing files (including ADS) with callback

Introduction

This is my first attempt to write an article for codeproject.com. I have written a useful and extremely simple C++ class for listing files in a directory. I skipped recursive searching just to keep article focused on basic class style.   

Background  

Reader can read about ADS (Alternate Data Streams).

Using the code    

It has two functions to list files in a given directory with the same name (overloaded). The class looks something like following class diagram.     

The listDir functions are like following:   

C++
int listDir(wstring csvExt, unsigned int adsReq=0); 
int listDir(PInspectFile InspectFunction, unsigned int adsReq=0);

PInspectFile is a function pointer defined like following:

C++
typedef unsigned char   (*PInspectFile)( wstring wFilePath );
  1. int listDir(wstring csvExt, unsigned int adsReq=0);
  2. The first function takes the directory path and compares the extensions of each file against desired extension. If extension matches with desired one, it puts the filename in a public member variable ‘filenames’ which is defined like  vector<wstring> filenames;.

  3. int listDir(PInspectFile InspectFunction, unsigned int adsReq=0);
  4. The second function takes the directory path and checks the file according to a callback function. It computes the complete path of the file and then calls the provided callback function. If callback function returns 1 then it puts the filename in a public member variable ‘filenames’ which is defined like following 

    C++
    vector<wstring> filenames;

Here is one sample callback function:

C++
unsigned char InspectFunction( wstring wFilePath){
  char ret=0; 
  DWORD dwType;
  if( GetBinaryType(wFilePath.c_str(), &dwType) ){
        if( (dwType == SCS_32BIT_BINARY)|| (dwType == SCS_64BIT_BINARY) )
              ret = 1;
  } 
  return ret; 
}

If user does not want ADS to be listed, no need to pass argument ‘adsReq’. It is set default to 0. But if user wants to list ADS also, then pass value 1 in the argument adsReq. If adsReq is 1, then listdir functions will also call member function GetStreams(wstring argFilename). With this class, a main program will look like this:

C++
CListDir    sample; 

sample.SetDirectoryPath(dirPath); 
sample.listDir(InspectFunction, 0);
while( i < sample.filenames.size() ) {
    wcout<<sample.filenames[i]<<endl;
    i++;
}

Points of Interest 

I posted this article because I thought simplicity of this class may be useful to some. And I found the idea of listing file based on callback function and clubbing with ADS a little bit interesting.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)