I'm working on writing some test cases for a class that will presumably read from an std::istream
and write to an std::ostream
. As part of the testing process, I would like to manually create a block of test file data, wrap it in a std::stringstream
, and then pass it to my class for processing.
I feel like my current solution lacks is lacking despite the fact that it does work. I really don't like using those raw write calls with reinterpret_cast
.
std::stringstream file;
uint32_t version = 1;
uint32_t dataSize = 10;
uint32_t recordCount = 3;
file.write(reinterpret_cast<char*>(&version), sizeof(version));
file.write(reinterpret_cast<char*>(&dataSize), sizeof(dataSize));
file.write(reinterpret_cast<char*>(&recordCount), sizeof(recordCount));
myclass.read(file)
Is there a way I can use the stream operators to write this data in binary form? I'm hoping for something more akin to the following.
std::stringstream file;
uint32_t version = 1;
uint32_t dataSize = 0;
uint32_t recordCount = 3;
file << version << dataSize << recordCount;
myclass.read(file);
If I go this route, extracting a number results in 103
which is expected in an ascii context, but I'm obviously trying to avoid serializing my data in that manner.