【问题标题】:C file read leaves garbage charactersC文件读取留下垃圾字符
【发布时间】:2010-04-22 13:31:12
【问题描述】:

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

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

【问题讨论】:

  • “偶尔”是什么意思?对于同一个文件,有时会得到垃圾字节,有时却不会?
  • 似乎发生了不同的事情,具体取决于我阅读它们的顺序,不过我不确定。这很奇怪。感谢您顺便编辑问题。如你所见,我是新人。

标签: c gcc file-io stdio


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多