[英]C reading from file, it reads “@”
I am trying to read a file in C. But when I read, and write it to stdout it prints @ also which there is no in my file. 我试图读取C中的文件。但是当我读取并将其写入stdout时,它会打印@,但我的文件中没有此文件。 What is the reason?
是什么原因?
#include <stdio.h>
int main() {
FILE *fp;
int br;
char buffer[10];
int i;
fp = fopen("a.txt","r");
while(1) {
br = fread(buffer,1,10,fp);
printf("%s",buffer);
if (br==0)
break;
}
}
Output: 输出:
1234567891@2345678912@3456789 12@3456789 12@ 1234567891 @ 2345678912 @ 3456789 12 @ 3456789 12 @
The file: 123456789123456789123456789 文件:123456789123456789123456789
Your fread
call reads up to 10 bytes correctly, but printf
with %s
requires string to be null terminated. 您的
fread
调用最多可以正确读取10个字节,但是带有%s
printf
要求字符串以null终止。 You can fix it by increasing size of the buffer to be 11 bytes and after every call to fread
write zero at the end of data, ie buffer[br] = 0;
您可以通过将缓冲区的大小增加为11个字节并在每次
fread
调用之后在数据末尾写入零来解决此问题,即buffer[br] = 0;
. 。
The other way to go is to tell printf
what is the size of your data by calling printf("%.*s", br, buffer);
另一种方法是通过调用
printf("%.*s", br, buffer);
来告诉printf
您的数据大小是多少printf("%.*s", br, buffer);
. 。 You don't need to modify your buffer array then.
然后,您不需要修改缓冲区数组。
Dynamically allocate your buffer and have it be initialized to zeros like this: 动态分配缓冲区,并将其初始化为零,如下所示:
char *buffer = calloc(1, 11);
<do your read loop>
free(buffer)
This way you get the zero byte at the end which will terminate the string when printing it. 这样,您将在末尾得到零字节,这将在打印字符串时终止该字符串。 When C prints a string it expects it to be terminated by a NULL (or 0) byte.
当C打印一个字符串时,它期望它以NULL(或0)字节终止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.