阅读文本文件c ++

时间:2015-01-15 03:38:08

标签: c++ file opengl fseek

在使用opengl和c ++开发3D游戏时遵循本教程https://www.youtube.com/watch?v=rOzQ8jSOnbo我在fseek中收到错误:

char* ShaderInterface::loadTextFromFile(const char* file)
{
    FILE *currentFile = fopen(file, "rt");
    fseek(currentFile, 0, SEEK_END); // Thread 1: EXC_BAD_ACCESS
    int count = (int)ftell(currentFile);
    // ...
}

我确定这应该可行,因为git帐户中的源代码确实有效,但我确定可能有更好的方法来执行此操作。

1 个答案:

答案 0 :(得分:2)

当您致电fopen()时,您必须检查返回值。该函数可能会失败(例如,如果文件不存在):

FILE* currentFile = fopen(file, "rt");
if (currentFile) {
    // success
    fseek(currentFile, 0, SEEK_END);
    // etc.
}
else {
    // report error back about not being able to open file
    // check errno, maybe log perror(), etc...
}
相关问题