0

当我运行下面的代码时,它在 linux 中失败,但在 windows 中没有问题。文件名类似于“src/文件夹/文件”

char* loadProgSource(const char* filename, size_t* finalLength)
{
    char* returnStr;
    FILE* file = fopen(filename, "rb");
    if(file == NULL) return NULL;

    fseek(file, 0, SEEK_END);
    *finalLength = ftell(file);
    fseek(file, 0, SEEK_SET);

    returnStr = (char*) malloc(*finalLength+1);

    if(fread(returnStr, sizeof(char), *finalLength, file) != *finalLength) {
        fclose(file);
        free(returnStr);
        return NULL;
    }
    returnStr[*finalLength] = '\0';

    return returnStr;
}
4

1 回答 1

1

不仅用于perror()在系统命令失败的情况下进行调试。

您可以像这样修改代码:

...

if (file == NULL) 
{
    perror("fopen");
    return NULL;
}

...

returnStr = malloc(*finalLength+1); /* note that casting 'malloc()' is not necessary and also not recommended uin C */
if (!returnStr)
{
  perror("malloc");
  return NULL;
}

...

if (fread(returnStr, sizeof(char), *finalLength, file) != *finalLength) 
{
  perror("fread");
  ...

fseek()对,ftell()和的调用添加错误检查fclose()作为练习。

于 2012-11-19T16:44:39.850 回答