Skip to content

Instantly share code, notes, and snippets.

@RuRo
Last active October 3, 2017 08:01
Show Gist options
  • Save RuRo/7e952b5157b013dbe8ecccf8b34105f0 to your computer and use it in GitHub Desktop.
Save RuRo/7e952b5157b013dbe8ecccf8b34105f0 to your computer and use it in GitHub Desktop.
Simple `read()` wrapper for reading blocks without bothering with size checks.
// Requirements
//-----------------
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
//-----------------
// Reads a block of `count` bytes. If less than `count` bytes is available,
// fills the rest of `buf` with 0. Returns the number of bytes actually read.
// Note: Unlike read(), if the return value is less than `count`, it is
// guaranteed that the file has ended.
size_t bread(int fd, char *buf, size_t count)
{
ssize_t temp = 0;
size_t done = 0;
while ((temp = read(fd, buf, count)))
{
if (temp < 0)
{
if (errno != EINTR) { exit(-errno); }
continue;
}
count -= temp;
done += temp;
buf += temp;
}
memset(buf, 0, count);
return done;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment