#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>

#define SIZE 1024

int main(int argc, char** argv) {
  if (argc != 2) {
    fprintf(stderr, "Usage: ./filedump <filename>\n");
    _exit(1);
  }

  int fd = open(argv[1], O_RDONLY);
  if (fd == -1) {
    fprintf(stderr, "Could not open file for reading\n");
    _exit(1);
  }

  char buf[SIZE];
  size_t len;

  do {
    len = read(fd, buf, SIZE);
    if (len == -1) {
      if (errno != EINTR) {
        close(fd);
        perror(NULL);
        _exit(1);
      }
      continue;
    }

    size_t total = 0;
    size_t wlen;
    while (total < len) {
      wlen = write(1, buf + total, len - total);
      if (wlen == -1) {
        if (errno != EINTR) {
          close(fd);
          perror(NULL);
          _exit(1);
        }
        continue;
      }
      total += wlen;
    }
  } while (len > 0);

  close(fd);
  return 0;
}