2010-04-22 2 views
1

파일의 내용을 내 프로그램으로 읽으려고하고 있지만 가끔 버퍼 끝에 가비지 문자가 표시됩니다. 나는 C를 많이 사용하지 않고있다. (오히려 나는 C++을 사용 해왔다.)하지만 스트림과 관련이 있다고 가정한다. 나는 정말로 무엇을해야하는지에 관해 모른다. MinGW를 사용하고 있습니다. 여기 C 파일 읽기가 가비지 문자를 남깁니다.

(이 상기 제 2 판독의 마지막 날 쓰레기를 준다) 코드이다

#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

"가끔"은 무엇을 의미합니까? 같은 파일에 대해 때때로 가비지 바이트를 얻고 때로는 그렇지 않습니까? –

+0

내가 읽은 주문에 따라 다른 일이 일어난 것처럼 보였습니다. 확실하지 않습니다. 이상했다. 그런데 질문을 편집 해 주셔서 감사합니다. 나는 당신이 보는 것처럼 새로운 사람이다. –

답변

1

버퍼를 지워야합니다. malloc은 그렇게하지 않습니다. 대신 calloc을 사용하거나 버퍼를 memset하는 것이 좋습니다.

+0

두 답변이 모두 작동하는 것 같습니다. 감사합니다 :) –

1

(..., "r") 대신 fopen (...., "rb")을 사용하십시오. Windows에서 이진 모드로 파일을 엽니 다.

+0

두 답변을 모두 작동하는 것. 감사 :) –