我有这个代码:
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
获取该值以在另一个函数中使用它?
最佳答案
替换行
findFile(nextPath, fileName);
与
char * f = findFile(nextPath, fileName);
if (f != NULL)
return f;
您需要检查返回值是否为 NULL - 如果为 NULL,您需要继续查找。
您还必须在函数末尾返回 NULL 以指示在该迭代中未找到任何内容。并非所有代码路径都返回一个值是“未定义的行为”——这意味着任何事情都可能发生。例如,如果您没有找到任何东西(即返回 NULL),您可能会返回虚假地址而不是您想要的地址。
还有一些其他问题 - 所有这些 malloc 都会导致内存泄漏并且没有释放,但是先让它工作然后再解决它。
关于c - 我无法从递归函数中正确返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40367419/