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. 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@
The file:
123456789123456789123456789
Dynamically allocate your buffer and have it be initialized to zeros like this:
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.