S. Casey S. Casey - 6 months ago 63
C++ Question

How can i create a istream from a uint8_t vector?

I am in the process of adding the ability to get data over the network to code that used to only read local files. The network library I am using sends and receives data in the form of a

vector<uint8_t>
. I'd like to be able to reuse the code that processes the data after reading the file, but that code expects a std::istream, is there a way to have an istream read the vector data? It's the same data so I feel like there should be a way, but i haven't been able to find or figure out code for how to do it.

current code:

std::ifstream stream("data.img", std::ios::in | std::ios::binary | std::ios::ate);

if (!stream.is_open())
{
throw std::invalid_argument("Could not open file.");
}
// the arg for processData is std::istream
processData(stream);


network framework:

vector<uint8_t> data = networkMessage.data;

// need some way to create istream from data
std::istream stream = ?

processData(stream);
stream.close();


Is there a way to do this, or am I barking up the wrong tree?

Answer Source

You can do this via assigning the data to a std::string and use a std::istringstream bound to that (leaving aside the unsigned char to signed char conversion issues):

std::string s((char*)networkMessage.data(),networkMessage.size());
std::istringstream iss(s);

std::istream& stream = iss;
         // ^ Note the reference here.

processData(stream);
stream.close();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download