I think what's happening here is that the input file already has CRLF line delimiters and you have opened it in text mode. What happens then is you use fread
, and it translates those to a line feed ('\n'
).
Since you asked for the file size first, that will be 6 bytes longer than the length of the translated text you read in. That means the last 6 bytes are uninitialised before you terminate the buffer at position flen
.
fread
will actually return the number of bytes read. You should pay attention to this value.
size_t bytes_read = fread(buffer, 1, flen, fp);
Try it. Output the value of bytes_read
and the value of flen
. I'll bet they're different. Also, you really don't have to terminate your buffer and use strlen
to get the length. It's actually quite ugly to do that. You already know the length -- it's bytes_read
. So use that in your loop.
If you want to avoid this confusion, you should open the file in binary mode -- "rb"
, not "r"
.