1

So, I have a class

class MySuperClass {
public:
 std::string buffer;
};

And wants to print buffer to std::cout. Here's some code about filling string from a file:

MySuperClass msc;
std::fstream file("./favicon.ico", std::fstream::in | std::fstream::binary);
if (file.is_open()) {
 std::stringstream ss;
 while (!file.eof())
   ss << static_cast<uint8_t>(file.get());
 msc.buffer.assign(ss.str());
 file.close();
}

When I output string, all ok. It prints messy, but something. But when I call c_str() on the buffer and try to print, it prints nothing.

phuclv
  • 37,963
  • 15
  • 156
  • 475
shArky
  • 25
  • 4
  • 2
    @phuclv your comment should've been answer. – Wander3r Oct 15 '20 at 07:24
  • @Wander3r Done. I was heading out last time so I had no time for an answer – phuclv Oct 15 '20 at 08:13
  • You should not expect to see anything sensible when you do this. Not all byte sequences can be interpreted as text at all, depending on the encoding you choose; and certainly in generally they will not be text that has any meaning. – Karl Knechtel Oct 15 '20 at 13:38

1 Answers1

3

An ICO file starts with 2 zero bytes so buffer.c_str() points to an empty string. As a result printing it shows nothing. If you print the byte values you'll immediately see why

for (const auto c: buffer)
    std::cout << std::setfill('0') << std::setw(2) << std::hex << +c << ' ';

OTOH std::string can contain embedded nulls, printing it outputs the whole file to the output stream

But why do you print a binary file as text in the first place? If you're on an ANSI terminal (like on Linux) it may mess up everything because there may be control characters in the byte stream and you can't ever see normal texts anymore until you reset the terminal

Besides you should read data in big blocks instead which is much faster than operating char-by-char

phuclv
  • 37,963
  • 15
  • 156
  • 475