
#include <iostream>

#include <windows.h>

#include < string>

#include <tchar.h>

#include <fstream>

using namespace std;

#ifdef _UNICODE

#define TCHAR wchar

# else

#define TCHAR char

#endif

//file stream

fstream fStream;

//count the total file number in the directory

static int fileCount=0;

void file_scan( char* root)

{

char filePath[MAX_PATH];

char tmpPath[MAX_PATH];

memset(filePath,0,MAX_PATH);

memset(tmpPath,0,MAX_PATH);

WIN32_FIND_DATA fd;

memset(&fd,0, sizeof(WIN32_FIND_DATA));

HANDLE hSearch;

strcpy(filePath, root);

BOOL bSearchFinished = FALSE;

if( filePath[strlen(filePath) -1] != '\\' )

{

strcat(filePath, "\\");

}

strcat(filePath, "*");

hSearch = FindFirstFile(filePath, &fd);

// the file is a dir , its name should not be '.','..', and not begin with '$'

if( (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)

&& (fd.cFileName[0]!='.') &&(fd.cFileName[0]!='$') )

{

strcpy(tmpPath, root);

strcat(tmpPath, fd.cFileName);

//recursion

file_scan(tmpPath);

}

// normal file

else if( strcmp(fd.cFileName, ".") && strcmp(fd.cFileName, "..")&& fd.cFileName[0]!='$')

{

cout<<root<<'\\'<<fd.cFileName<<endl;

fStream.write(root,strlen(root));

fStream.write("\\",1);

fStream.write(fd.cFileName,strlen(fd.cFileName));

fStream.write( "\r\n",2);

++fileCount;

}

while( !bSearchFinished )

{

if( FindNextFile(hSearch, &fd) )

{

if( (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)

&& strcmp(fd.cFileName, ".") && strcmp(fd.cFileName, "..") )

{

strcpy(tmpPath, root);

memset(tmpPath+strlen(tmpPath),0,MAX_PATH-strlen(tmpPath));

if(tmpPath[strlen(tmpPath)]!='\\')

{

tmpPath[strlen(tmpPath)]='\\';

tmpPath[strlen(tmpPath)+1]='\0';

}

strcat(tmpPath, fd.cFileName);

file_scan(tmpPath);

}

else if(strcmp(fd.cFileName, ".") && strcmp(fd.cFileName, "..")&& fd.cFileName[0]!='$')

{

cout<<root<<'\\'<<fd.cFileName<<endl;

fStream.write(root,strlen(root));

fStream.write("\\",1);

fStream.write(fd.cFileName,strlen(fd.cFileName));

fStream.write( "\r\n",2);

++fileCount;

}

}

else

{

if( GetLastError() == ERROR_NO_MORE_FILES ) //Normal Finished

bSearchFinished = TRUE;

else

bSearchFinished = TRUE; //Terminate Search

}

}

FindClose(hSearch);

}

int main( int argc, char** argv)

{

char dir[MAX_PATH];

char txtfile[MAX_PATH];

cout<< "please enter the directory to be scanned !"<<endl;

cin>>dir;

cout<<endl<<endl;

cout<< "Please input the .txt file name (include path) to record your search result !"<<endl;

cin>>txtfile;

cout<<endl<<endl;

fStream.open(txtfile,ios:: in | ios:: out);

if(!fStream)

{

cout<< "Can not open the .txt file"<<endl;

return 0;

}

cout<< "the file is opened !"<<endl;

file_scan(dir);

fStream.close();

cout<<endl<<endl;

cout<< "the total file number in "<<dir<< " : "<<fileCount<<endl;

return 0;

}