0

I have following piece of code to read data from a device:

    void handle_read(const boost::system::error_code& ec, std::size_t n) {
        std::cout << "handle_read: " << ec << " " << n << "\n";
        if (!ec) {
            std::istream stream(&buf);    
            while(!stream.eof()) {        
                char c[4096];
                stream.read(c, 4096);     //....(1)
                std::cout << "stream size: " << stream.gcount() << "\n";
                std::cout << std::hex << (0xFF & (unsigned char) c[0]) << " " <<     //....(2)
                     (0xFF & (unsigned char) c[1]) << " " << 
                     (0xFF & (unsigned char) c[2]) << " " << 
                     (0xFF & (unsigned char) c[3]) << "\n";
            }

            //Continue reading remaining data until EOF.
            boost::asio::async_read(*tcp_socket, buf,
                boost::asio::transfer_at_least(1),
                boost::bind(&Connection::handle_read, this,
                boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
    }

Without (1) and (2), num of bytes read in each cycle is around 1440. As I keep adding the steps, n reduces to 512 and 200 respectively.

What is the effect of istream.read() and std::cout on number of bytes read by async_read? Is there any way to avoid this?

harsh
  • 763
  • 1
  • 9
  • 18
  • 1
    Unrelated to your problem, but please read [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Some programmer dude Jul 23 '19 at 12:30
  • Thanks! I was wondering why I never get the `eof` error – harsh Jul 23 '19 at 12:40

1 Answers1

0

By

std::cout << std::hex

you have changed base for numeric.

So only at first handler call, you are printing the number of read bytes in decimal - 1440. In second and next calls of handler you are printing value of read bytes in hex base. You need to explicitly turn it back to decimal by dec manipulator. So 512 as hex is 1298 in decimal. I think this value is close to 1440.

rafix07
  • 17,659
  • 2
  • 14
  • 24