1

我正在尝试将文件的内容读入我的程序,但我偶尔会在缓冲区末尾收到垃圾字符。我没有经常使用 C(我一直在使用 C++),但我认为它与流有关。我真的不知道该怎么做。我正在使用 MinGW。

这是代码(这在第二次阅读结束时给了我垃圾):

#include <stdio.h>
#include <stdlib.h>

char* filetobuf(char *file)
{
    FILE *fptr;
    long length;
    char *buf;

    fptr = fopen(file, "r"); /* Open file for reading */
    if (!fptr) /* Return NULL on failure */
        return NULL;
    fseek(fptr, 0, SEEK_END); /* Seek to the end of the file */
    length = ftell(fptr); /* Find out how many bytes into the file we are */
    buf = (char*)malloc(length+1); /* Allocate a buffer for the entire length of the file and a null terminator */
    fseek(fptr, 0, SEEK_SET); /* Go back to the beginning of the file */
    fread(buf, length, 1, fptr); /* Read the contents of the file in to the buffer */
    fclose(fptr); /* Close the file */
    buf[length] = 0; /* Null terminator */

    return buf; /* Return the buffer */
}

int main()
{
 char* vs;
 char* fs;

 vs = filetobuf("testshader.vs");
 fs = filetobuf("testshader.fs");

 printf("%s\n\n\n%s", vs, fs);

 free(vs);
 free(fs);

 return 0;
}

filetobuf 函数来自此示例http://www.opengl.org/wiki/Tutorial2:_VAOs,_VBOs,_Vertex_and_Fragment_Shaders_%28C_/_SDL%29。不过对我来说似乎是对的。

所以不管怎样,这是怎么回事?

4

2 回答 2

1

您需要清除缓冲区 - malloc 不会这样做。尝试使用 calloc 或 memset'ing 你的缓冲区,以便它开始清晰。

于 2010-04-22T13:34:36.357 回答
1

使用 fopen(.... , "rb") 代替 (..., "r"); 在 Windows 下以“二进制”模式打开文件。

于 2010-04-22T13:36:15.433 回答