Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

show full string from string with \0 chars

Tags:

c++

std

char data_[4096];
...
socket_.async_read_some(boost::asio::buffer(data_, 4096),
    boost::bind(&client::handle_read_header, this,
    boost::asio::placeholders::error,
    boost::asio::placeholders::bytes_transferred));

when function handle_read_header is fired, data_ contains many \0 symbols in text. with help of which way is it easier to view full (with stripped or escaped \0) string by std::cout? (by default \0 make end of string and don't show other)

like image 943
askovpen Avatar asked Jul 23 '26 14:07

askovpen


2 Answers

Seth kindly pointed out your requirement to make it "easier to view". For that:

for (size_t i = 0; i < num_bytes; ++i)
    if (buffer[i] == '\\')
        std::cout << "\\\\";
    else if (isprint(buffer[i]))
        std::cout << buffer[i];
    else
        std::cout << '\\' << std::fill(0) << std::setw(3) << buffer[i];

The above uses 3-digit back-slash escaped octal notation to represent non-printable characters. You can change the representation easily enough.

(For a simple binary write, you can call std::cout.write(buffer, num_bytes) to do a binary block write, rather than std::cout << buffer which relies on the ASCIIZ convention for character arrays/pointers. Then you could pipe the result into less, cat -vt or whatever your OS provides that helps view binary data including NULs.)

like image 72
Tony Delroy Avatar answered Jul 25 '26 06:07

Tony Delroy


std::transform( data_, data_+size, std::ostream_iterator<char>(std::cout)
              , [](char c) { c == 0 ? '*':c; });

You can pick anything besides '*' of course. If you can't use the current C++ facilities then just make a function that does what the above lambda does.

like image 37
Edward Strange Avatar answered Jul 25 '26 08:07

Edward Strange



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!