OK, I can't find a decent duplicate - maybe someone else will.
The line
fread(buffer, sizeof(buffer), 1, file_);
potentially fills your buffer completely. You need to keep the return value to know how many bytes were actually written, but assuming your file contained at least five bytes, all five bytes of your buffer array are now initialized.
However, to print buffer as a regular C string, it needs a sixth byte, containing the null terminator.
For example, the C string "12345" is actually represented as the char array {'1', '2', '3', '4', '5', 0}.
You don't have room for a terminator in your buffer, and don't write one, so you can't treat it as a simple C string.
Your options are:
- add a terminator manually, as in Martin Bonner's answer
don't add a terminator, but track the size - you can use the C++17
std::string_view bufstr(buffer, nchars);
to keep the pointer and size together (and you can print this normally)
- stop using the old C I/O library entirely. The C++ I/O library admittedly doesn't have a much better way to read groups of five characters, but reading whole lines, for example, is much easier to do correctly.
std::stringandstd::ifstreamand save yourself a lot of effort.sizeof(buffer)tosizeof(buffer) - 1, in order to avoid overriding the null character.freadin a while, so I've figured out of the back of my memory that it adds the null character after the amount of characters requested.