fopen 在 Linux 中失败,但在 Windows 中工作

2024-01-31

当我运行下面的代码时,它在 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;
}

不仅仅用于调试使用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() and fclose()留作练习。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

fopen 在 Linux 中失败,但在 Windows 中工作 的相关文章

随机推荐