2010-04-22 31 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