I want to read 80 characters from a text file, save them to a string and then print that string for verification.
I am using fread and have this code:
char message[80];
size_t nread = fread(message, 1, sizeof(message), fp);
printf("Message received: \"__%s__\"\n", message);
And the output is:
Message received: “__I would love to change the world but they won’t
��__”
when the whole phrase isn’t in the file
and:
__I would love to change the world but they won’t give me the source code
@__
when the whole phrase is in the file.
I’ve tried deleting it and rewriting the text but I get the same output again.
What is wrong? Something with the charset?
fread()does not null terminate the buffer andprinf("%s")expects the buffer to be null terminated. As the buffer is not null terminatedprintf()will continue reading until it finds a null terminator, printing out any junk along the way.Either null terminate the buffer, remembering to leave room for the null terminator:
or instruct
printf()to only print the number of characters read using"%.*s"format specifier: