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

#define SIZE   200

int main (int argc, char ** argv)
{
   int fd;
   int nread, nwrite;
   char buff[SIZE];

   // make sure we have exactly one commandline argument, argv[1]
   assert (argc == 2);

   // open the file
   fd = open (argv[1], O_RDONLY);

   // check for errors
   if (fd < 0)
   {
      fprintf (stderr, "cannot open file\n");
      exit (1);
   }

   while (1)
   {
      // read data from fd
      nread = read (fd, buff, SIZE);

      // handle errors
      if (nread < 0)
      {
         fprintf (stderr, "read error\n");
         exit (1);
      }

      // check for end of file
      if (nread == 0) break;

      // write the data to the standard output
      nwrite = write (1, buff, nread);

      // check for errors while writing
      if (nwrite < 0)
      {
         fprintf (stderr, "write error\n");
         exit (1);
      }

      // incomplete write (nwrite != nred)
      if (nwrite != nread)
      {
         fprintf (stderr, "partial write, I cannot handle this\n");
         exit (1);
      }
   }

	// close fd file descriptor
	close (fd);

   // all data writen to fd 1
   return 0;
}

