为什么我的简单的C程序显示垃圾到标准输出? [英] Why is my simple C program displaying garbage to stdout?
问题描述
考虑一个文件读入缓冲区,并显示该缓冲区到控制台下面简单的C程序:
Consider the following simple C program that read a file into a buffer and displays that buffer to the console:
#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);
}
它只会读取的文件包括:
The file it will read simply contains:
世界,你好!
输出是:
世界,你好!²²²²▌▌▌▌▌▌▌↔☺
Hello World!²²²²▌▌▌▌▌▌▌↔☺
这已经有一段时间,因为我做了什么在C / C ++显著,但通常我会假设正在分配的缓冲区大于必需的,但是这似乎并不如此。
It has been a while since I did anything significant in C/C++, but normally I would assume the buffer was being allocated larger than necessary, but this does not appear to be the case.
fileLen结束是12,这是正确的。
fileLen ends up being 12, which is accurate.
我现在想,我一定只是显示缓冲区错了,但我不知道我做错了。
I am thinking now that I must just be displaying the buffer wrong, but I am not sure what I am doing wrong.
任何人都可以给我介绍一下我做错了?
Can anyone clue me in to what I am doing wrong?
推荐答案
您需要NUL,终止字符串。添加
You need to NUL-terminate your string. Add
buffer[fileLen] = 0;
在打印。
这篇关于为什么我的简单的C程序显示垃圾到标准输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!