Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading raw byte array into std::string

Tags:

c++

string

I've been wondering about the following issue: assume I have a C style function that reads raw data into a buffer

int recv_n(int handle, void* buf, size_t len);

Can I read the data directly into an std:string or stringstream without allocating any temporal buffers? For example,

std::string s(100, '\0');
recv_n(handle, s.data(), 100);

I guess this solution has an undefined outcome, because, afaik, string::c_str and string::data might return a temporal location and not necessarily return the pointer to the real place in the memory, used by the object to store the data.

Any ideas?

like image 534
FireAphis Avatar asked Dec 23 '10 16:12

FireAphis


People also ask

How many bytes is a std::string?

Example. In below example for std::string::size. The size of str is 22 bytes.

Is std::string a container?

std::string is not a Container for Raw Data Serialized binary data that has to be interpreted before it can be used in our business logic. The natural way to manage this kind of data is having sequence containers like std::vector or std::array of std::byte or, lacking C++17 support, unsigned char .

What is std::string data?

std::string::data Returns a pointer to an array that contains the same sequence of characters as the characters that make up the value of the string object.


2 Answers

Why not use a vector<char> instead of a string? That way you can do:

vector<char> v(100, '\0');
recv_n(handle, &v[0], 100);

This seems more idiomatic to me, especially since you aren't using it as a string (you say it's raw data).

like image 165
chrisaycock Avatar answered Oct 26 '22 23:10

chrisaycock


Yes, after C++11.

But you cant use s.data() as it returns a char const*

Try:

std::string s(100, '\0');
recv_n(handle, &s[0], 100);

Depending on situation, I may have chosen a std::vector<char> especially for raw data (though it would all depend on usage of the data in your application).

like image 28
Martin York Avatar answered Oct 27 '22 01:10

Martin York