Skip to content

Instantly share code, notes, and snippets.

@sw17ch
Created December 10, 2014 23:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sw17ch/0bd0c7c61ff1854cc1a4 to your computer and use it in GitHub Desktop.
Save sw17ch/0bd0c7c61ff1854cc1a4 to your computer and use it in GitHub Desktop.
Read from a file handle until you get all the bytes or an error happens.
/*
* read_exactly
*
* Automatically re-reads a file descriptor until an error occurs or the
* expected number of bytes has been read.
*
* fd - the file descriptor to read from.
* buf - the buffer to read into.
* nbyte - the number of bytes to read into the buffer.
* rbyte - the actual number of bytes read into the buffer. Will always
* equal nbyte if all reads were successful.
*
* Returns true when no errors occurred and the proper number of bytes was
* read. Returns false otherwise.
*/
bool read_exactly(int fd, void * buf, size_t nbyte, size_t * rbyte) {
size_t r = 0;
while(r < nbyte) {
int l = read(fd, buf, nbyte - r);
if (l <= 0) {
break;
} else {
r += l;
}
}
if (rbyte) {
*rbyte = r;
}
return (r == nbyte);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment