开发者

How to push binary data into std::string?

Im trying to create a binary file in the following way:

string buf;
...
buf += filename.length();
buf += filename;

etc. So first i give the length in binary format, b开发者_开发技巧ut how do i convert this into a 4 byte char array, or 2 byte etc? basically i want to achieve the same functionality as this would:

int len = filename.length();
fwrite(&len, sizeof(len), 1, fp);

Which works fine, but having it in one string might be easier to process.

Edit: i dont want to use streams, nor vector, im trying to find out if its possible with strings.


Streams are the way to go. Not strings.


Use a vector for holding the data, or write it straight to the file (via streams)


simply use std:vector<unsigned char> and use a istream or ostream iterator to read/write data to/from the vector. For instance to read from a file you can do:

vector<unsigned char> binary_buffer;

ifstream in_file("my_binary_file.bin", ios_base::binary | ios_base::in);
istream_iterator<unsigned char> end_of_file;
istream_iterator<unsigned char> in_file_iter(in_file);

while (in_file_iter != end_of_file)
{
    binary_buffer.push_back(*in_file_iter++);
}

Output would be even simpler:

ofstream out_file("another_binary_file.bin", ios_base::binary | ios_base::out);
ostream_iterator<unsigned char> binary_output(out_file);
copy(binary_buffer.begin(), binary_buffer.end(), binary_output);


Yes, it is possible to do this, because this is C++, and everything is possible in C++.

First, here is how you do it, then I'll answer the question of why you might need to do it:

std::ifstream input( "my.png", std::ios::binary );
std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(input), {});
int buffSize = buffer.size();
std::string myString(buffer.begin(), buffer.end());

In my case, I was using a framework where the HTTP Client only supported a string for post message body, but I needed to post raw binary of a file to the service I was using. I could either mess around with the internals of the library (bad) or introduce another unnecessary dependency for a simple file post (also not so good).

But since strings can hold this data, I was able to read the file, copy it to a string and then upload.

This is an unfortunate situation to be in, either way, but in some cases it is helpful to be able to do. Usually you would want to do something different. This isn't the clearest for someone else to read, and you will have some performance penalties from the copy, but it works; and it helps to understand the internals of why it works. std::string saves the data contiguously internally in binary format, like vector does, and can be initialized from iterators in the vector.

unsigned char is one byte long, so it is like a byte value. The string copies the bytes into itself, so you end up with the exact data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜