我无法从递归函数中正确返回

时间:2016-11-01 19:37:53

标签: c recursion

我有这段代码:

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;
        }
    }
  }
}

有一次,该函数返回foundPath,但我不知道如何拾取它并从第一个函数调用返回它。我可以打印它以确保函数有效,但是我可以做些什么来从foundPath获取该值以在另一个函数中使用它?

2 个答案:

答案 0 :(得分:4)

替换

findFile(nextPath, fileName);

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

您需要检查返回值是否为NULL - 如果它是NULL,您要继续查看。

您还必须在函数末尾返回NULL,以指示在该迭代中未找到任何内容。没有所有代码路径返回值是“未定义的行为” - 这意味着任何事情都可能发生。例如,如果您没有找到任何内容(返回NULL),您可能会返回虚假地址而不是您想要的地址。

还有一些其他问题 - 所有mallocs都没有内存泄漏而且没有释放,但要先让它工作然后解决它。

答案 1 :(得分:1)

也许这样做:

return findFile(nextPath, fileName);

而不是:

findFile(nextPath, fileName);