C文件读取留下乱码

标签 c gcc file-io stdio

我正在尝试将文件的内容读入我的程序,但我偶尔会在缓冲区末尾收到垃圾字符。我并没有经常使用 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 .不过对我来说这似乎是对的。

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

最佳答案

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

关于C文件读取留下乱码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2691213/

相关文章:

c++ - 指针数组,如 (*(volatile unsigned long *)0x40004000)

perl - 有没有办法在 Perl 中创建在创建时锁定的文件?

performance - 从具有增强性能的文本文件中删除重复出现的行

c - 为什么将 "extern puts"转换为函数指针 "(void(*)(char*))&puts"?

c - const static int 数组

c - autotools:启用编译器警告

c - 宏作为另一个宏的参数

xcode - 为什么 Homebrew 报告 "couldn' t 理解 kern.osversion `14.0.0'”?

c - `({...})` 是如何返回值的?

.net - 在高负载的 .ashx http 处理程序中将记录附加到磁盘文件的最快、最安全的方法是什么?