Thursday, May 21, 2009

Recursive Method to list all the file present in a Directory using cpp



#include < iostream >
#include < dirent.h >

using namespace std;

class recDir
{
private:
int fileCount;
public:
recDir()
{
fileCount = 0;
}
void showFileList(char *dirPath)
{
char *subDir="",*temp;
DIR *curDir;
struct dirent *entry;
if(curDir = opendir(dirPath))
{
while(entry = readdir(curDir))
{
if(strcmp(entry- > d_name,".") != 0 &&
strcmp(entry- > d_name,"..") != 0)
{
temp=strstr(entry- > d_name,".");
if(temp!=NULL
{
fileCount++;
cout << "File [" <<
fileCount << "] " <<
entry- > d_name << endl;
}
else
{
subDir = dirPath;
strcat(subDir,"/");
strcat(subDir,entry- > d_name);
showFileList(subDir);
}
}
}
closedir(curDir);
}
else
cout << "Error:Could not open directory/file\n";
}
int totalFiles()
{
return fileCount;
}
};


int main(int argc,char *argv[])
{
recDir obj;
obj.showFileList(argv[1]);
cout << endl << "Total Files =
" << obj.totalFiles() << endl;
}

2 comments:

  1. yea.....system("ls -lr") will print all the files and folders.....But here necessity is to print only files recursively.

    ReplyDelete

Search Ranjeet's Blog