考虑以下简单的C程序,该程序将文件读入缓冲区并将该缓冲区显示到控制台:
#include<stdio.h>
main()
{
FILE *file;
char *buffer;
unsigned long fileLen;
//Open file
file = fopen("HelloWorld.txt", "rb");
if (!file)
{
fprintf(stderr, "Unable to open file %s", "HelloWorld.txt");
return;
}
//Get file length
fseek(file, 0, SEEK_END);
fileLen=ftell(file);
fseek(file, 0, SEEK_SET);
//Allocate memory
buffer=(char *)malloc(fileLen+1);
if (!buffer)
{
fprintf(stderr, "Memory error!");
fclose(file);
return;
}
//Read file contents into buffer
fread(buffer, fileLen, 1, file);
//Send buffer contents to stdout
printf("%s\n",buffer);
fclose(file);
}
Run Code Online (Sandbox Code Playgroud)
它将读取的文件只包含:
你好,世界!
输出是:
Hello World!²²²²
已经有一段时间了,因为我在C/C++中做了很多重要事情,但通常我会认为缓冲区的分配大于必要的,但事实并非如此.
fileLen最终为12,这是准确的.
我现在在想,我必须只是显示错误的缓冲区,但我不确定我做错了什么.
谁能让我知道我做错了什么?