Question

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

Was it helpful?

Solution

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.

OTHER TIPS

Your fread call reads up to 10 bytes correctly, but printf with %s requires string to be null terminated. 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, i.e. 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);. You don't need to modify your buffer array then.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top