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:
int listDir(wstring csvExt, unsigned int adsReq=0);
int listDir(PInspectFile InspectFunction, unsigned int adsReq=0);
PInspectFile
is a function pointer defined like following:
typedef unsigned char (*PInspectFile)( wstring wFilePath );
int listDir(wstring csvExt, unsigned int adsReq=0);
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;
.
int listDir(PInspectFile InspectFunction, unsigned int adsReq=0);
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
vector<wstring> filenames;
Here is one sample callback function:
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:
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.