Skip to content

Instantly share code, notes, and snippets.

@ochinchina
Created July 2, 2014 10:09
Show Gist options
  • Save ochinchina/e6d65abc2508e528084a to your computer and use it in GitHub Desktop.
Save ochinchina/e6d65abc2508e528084a to your computer and use it in GitHub Desktop.
read bytes to a buffer from C++ std::istream
#include <iostream>
std::size_t read_bytes( std::istream& in, char* buf, std::size_t len ) {
std::size_t n = 0;
while( len > 0 && in.good() ) {
in.read( &buf[n], len );
int i = in.gcount();
n += i;
len -= i;
}
return n;
}
int main( int argc, char** argv ) {
std::istringstream in( "this is a test stream");
char buf[100];
std::size_t n = read_bytes( in, buf, sizeof( buf ));
assert( n < 100 );
}
@mavlyut
Copy link

mavlyut commented Oct 29, 2023

You can use rdbuf->sgetn method:

std::size_t read_bytes( std::istream& in, char* buf, std::size_t len ) {
	return in.rdbuf()->sgetn(buf, len);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment