/////////////////////////////////////////////////////////////// // dir2.cpp - traverse subtree below current directory // // // // Adapted by Jim Fawcett from the book: // // "Win32 System Services: // // The Heart of Windows 95 and Windows NT", Marshall Brain, // // Prentice Hall, Copyright 1995 // // // /////////////////////////////////////////////////////////////// // Note: fixed bug in published code which fails to report // // directory change to parent, associating files with // // incorrect directory // /////////////////////////////////////////////////////////////// #include #include #include #include using namespace std; //----< prints information about a file >---------------------- void PrintFindData(WIN32_FIND_DATA *findData) { cout << setw(20) << findData->cFileName; cout << setw(10) << findData->nFileSizeLow << endl; } //----< Recursively lists directories >------------------------ void ListDirectoryContents(char *dirName, char *fileMask) { char *fileName; char curDir[ 256 ]; char fullName[ 256 ]; char prevFullName[256]; HANDLE fileHandle; WIN32_FIND_DATA findData; // save current dir so it can restore it if( !GetCurrentDirectory( 256, curDir) ) return; // // if the directory name is neither . or .. then // change to it, otherwise ignore it if( strcmp( dirName, "." ) && strcmp( dirName, ".." ) ) { if( !SetCurrentDirectory( dirName ) ) return; } else return; // print out the current directory name strncpy(prevFullName,fullName,256); if( !GetFullPathName( fileMask, 256, fullName, &fileName ) ) return; if(strcmp(fullName,prevFullName) != 0) cout << " " << fullName << endl; // Loop through all files in the directory fileHandle = FindFirstFile( fileMask, &findData ); while ( fileHandle != INVALID_HANDLE_VALUE ) { // If the name is a directory, // recursively walk it. Otherwise print // print the file's data if( findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { ListDirectoryContents( findData.cFileName, fileMask ); } else PrintFindData( &findData ); // loop thru remaining entries in the dir if (!FindNextFile( fileHandle, &findData )) break; } // clean up and restore directory FindClose( fileHandle ); SetCurrentDirectory( curDir ); // print out the current directory name strncpy(prevFullName,fullName,256); if( !GetFullPathName( fileMask, 256, fullName, &fileName ) ) return; if(strcmp(prevFullName,fullName) != 0) cout << " " << fullName << endl; } // //----< test stub >-------------------------------------------- int main(int argc, char *argv[]) { cout << "\n Demonstrating Directory Traversal " << "\n ===================================\n\n"; char curDir[ 256 ]; if( !GetCurrentDirectory( 256, curDir ) ) { cerr << "Couldn't get the current directory." << endl; return( 1 ); } // List all files, starting with the current directory ListDirectoryContents( curDir, "*.*" ); cout << endl; return( 0 ); }