Function recursion searching for files in directory

17 Views Asked by At

I'm trying to write a program to search the hard drive for a file specified by the user. However, when I run the program, I either get 'stack overflow' errors or it doesn't properly walk all directories.

This program is written for MS-DOS real mode in C89/C with classes. Here are my functions:

void FindFile( const char *SearchPath, const char *Filename )
{
    struct FIND *found;
    char OutputPath[_MAX_PATH];
    char PathBuffer[_MAX_PATH];
    char *Directories[_MAX_PATH];
    short ChDirResult;

    ChDirResult = _chdir( (char*)SearchPath );
    if ( ChDirResult != 0 ) {
        perror( "\rFailed to change directory" );
        return;
    }

    // search directories first
    GetDirectories( Directories, SearchPath );
    if ( Directories[0] != NULL ) {
        for ( unsigned long i = 0; i < ( sizeof( Directories ) / sizeof( Directories[0] ) ); ++i ) {
            FindFile( Directories[i], Filename );
        }
    }

    // search files next
    strncpy( PathBuffer, SearchPath, _MAX_PATH );
    strncat( PathBuffer, Filename, _MAX_FNAME + _MAX_EXT + 1 );
    found = findfirst( PathBuffer, _A_RDONLY | _A_HIDDEN | _A_SYSTEM | _A_ARCH | _A_NORMAL );
    while ( found != NULL ) {
        printf( "\n%s", _fullpath( OutputPath, _strupr( found->name ), _MAX_PATH ) );
        found = findnext();
    }
}

void GetDirectories( char *Directories[], const char *Path )
{
    struct FIND *found;
    char SearchPath[_MAX_PATH];

    strcpy( SearchPath, Path );
    strcat( SearchPath, "*.*" );

    found = findfirst( SearchPath, _A_SUBDIR );
    if ( found != NULL ) {
        for ( unsigned long i = 0; found != NULL; ++i ) {
            if ( found->attribute == _A_SUBDIR && ( strcmp( found->name, "." ) != 0 || strcmp( found->name, ".." ) != 0 ) ) {
                char dir[_MAX_PATH];
                _fullpath( dir, found->name, _MAX_PATH );
                strcat( dir, "\\" );
                strcpy( Directories[i], dir );
            }
            found = findnext();
        }
    }
}

What am I doing wrong?

0

There are 0 best solutions below