fopen在linux中失败,但在Windows中工作 [英] fopen fails in linux but works in windows
本文介绍了fopen在linux中失败,但在Windows中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我运行下面的代码时,它在Linux中失败,但Windows没有问题.文件名类似于"src/folder/file"
when i run the code below it fails in linux but no problem with windows. filename is something like "src/folder/file"
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()
.
Not only for debugging use perror()
in case a system command failed.
您可以这样修改代码:
...
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()
的调用中添加错误检查.
Adding error checking on the calls to fseek()
, ftell()
and fclose()
is left as an exercise.
这篇关于fopen在linux中失败,但在Windows中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文