[英]Reading raw byte array into std::string
I've been wondering about the following issue: assume I have a C style function that reads raw data into a buffer 我一直想知道以下问题:假设我有一个C样式函数将原始数据读入缓冲区
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? 我可以直接将数据读入
std:string
或stringstream
而无需分配任何时间缓冲区吗? 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. 我猜这个解决方案有一个未定义的结果,因为,afaik,
string::c_str
和string::data
可能会返回一个临时位置,并不一定会将指针返回到内存中的实际位置,由对象用来存储数据。
Any ideas? 有任何想法吗?
Why not use a vector<char>
instead of a string
? 为什么不使用
vector<char>
而不是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). 这对我来说似乎更惯用,特别是因为你没有将它用作字符串(你说它是原始数据)。
Yes, after C++11. 是的,在C ++ 11之后。
But you cant use s.data()
as it returns a char const*
但你不能使用
s.data()
因为它返回一个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). 根据具体情况,我可能选择了std :: vector <char>,尤其是原始数据(尽管这完全取决于应用程序中数据的使用情况)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.