2010-04-22 29 views
1

我试图读入一个文件的内容到我的程序中,但我偶尔会在缓冲区结尾处获取垃圾字符。我一直没有使用C(而是我一直在使用C++),但我认为它与流有关。我真的不知道该怎么做。我正在使用MinGW。C文件读取留下垃圾字符

下面是代码(这给了我垃圾在第二读取结束时):

#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。这对我来说似乎是正确的。

所以无论如何,这是怎么回事?

+0

你是什么意思“偶尔”?对于同一个文件,有时你会得到垃圾字节,有时你不会? – 2010-04-22 13:35:03

+0

不同的事情似乎正在发生取决于我读他们的顺序,我不确定。这很奇怪。 感谢您编辑问题的方式。你看,我是新的。 – 2010-04-22 13:45:56

回答

1

你需要清除你的缓冲区 - malloc不这样做。尝试使用calloc代替或memset你的缓冲区,以便它清楚地开始。

+0

这两个答案似乎工作。谢谢:) – 2010-04-22 13:45:25

1

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

+0

这两个答案似乎工作。谢谢 :) – 2010-04-22 13:44:53