Is there anyway to read a known number of bytes, directly into an std::string, without creating a temporary buffer to do so?
eg currently I can do it by
You could use a combination of copy_n and an insert_iterator
void test_1816319()
{
static char const* fname = "test_1816319.bin";
std::ofstream ofs(fname, std::ios::binary);
ofs.write("\x2\x0", 2);
ofs.write("ab", 2);
ofs.close();
std::ifstream ifs(fname, std::ios::binary);
std::string s;
size_t n = 0;
ifs.read((char*)&n, 2);
std::istream_iterator isi(ifs), isiend;
std::copy_n(isi, n, std::insert_iterator(s, s.begin()));
ifs.close();
_unlink(fname);
std::cout << s << std::endl;
}
no copying, no hacks, no possibility of overrun, no undefined behaviour.