读取文本文件 c++

Reading in a text file c++

本文关键字:c++ 文件 取文本 读取      更新时间:2023-10-16

按照本教程 https://www.youtube.com/watch?v=rOzQ8jSOnbo 使用 opengl 和 c++ 开发 3D 游戏时,我在 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 帐户中的源代码确实有效,尽管我确信可能有更好的方法来做到这一点。

当你调用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...
}