Alexandru Antochi
Alexandru Antochi

Reputation: 1465

I can't properly return from a recursive function

I have this code:

char* findFile(char* path, char* fileName)
{
DIR *thisDir;
struct dirent *dirEntry;

int notFound=1;

while (NULL != (dirEntry = readdir(thisDir)) && notFound)
{
    if (dirEntry->d_type == DT_DIR)
    {
        if (dirEntry->d_name[0] != '.')
        {
            char *nextPath = malloc(512);
            strcpy(nextPath, path);
            strcat(nextPath, dirEntry->d_name);
            nextPath[nextPathLen] = '/';
            findFile(nextPath, fileName);

        }
    }
    else if (dirEntry->d_type == DT_REG)
    {
        if (strcmp(fileName, dirEntry->d_name) == 0 )
        {
            char* foundPath = malloc (512);
            strcpy(foundPath,path);
            strcat(foundPath,fileName);
            notFound=0;
            return foundPath;
        }
    }
  }
}

At one point the function returns the foundPath but I don't know how to pick it up and return it from the first function call. I can print it to verity the function works, but what can I do to get that value from foundPath to use it in another function?

Upvotes: 1

Views: 89

Answers (2)

John D
John D

Reputation: 1637

Replace the line

findFile(nextPath, fileName);

with

char * f = findFile(nextPath, fileName);
if (f != NULL)
    return f;

You need to check the return value is not NULL - if it is NULL you want to keep looking.

You must also return NULL at the end of the function to indicate that nothing was found in that iteration. It is "undefined behaviour" to not have all code paths returning a value - that means anything could happen. Eg, you could get spurious addresses being returned instead of what you want in the case you don't find anything (which is to return NULL).

There are a few other issues - you'll have memory leaks with all those mallocs and no frees, but get it working first and then tackle that.

Upvotes: 4

Sergio
Sergio

Reputation: 864

Maybe doing this:

return findFile(nextPath, fileName);

Instead of:

findFile(nextPath, fileName);

Upvotes: 1

Related Questions