// Copy file whose name is given as a program argument to stdout

#include <stdio.h>
#include <stdlib.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];
  ssize_t len;

  do {
    len = read(fd, buf, SIZE);
    if (len == -1) {
      if (errno != EINTR) {
        close(fd);
        perror("Error reading file");
        exit(1);
      }
      continue;
    }

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

  close(fd);
  return 0;
}