/* head-1 
 *
 * Demonstrates using unbuffered I/O to print the first few bytes of a file
 *
 * Jerod Weinman
 * 24 June 2008
 */

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

#define NUM_BYTES 32 /* Number of bytes to read and print */

int main(int argc, char* argv[])
{
     int fd;                      /* File descriptor for reading file */
     int bytesRead, bytesWritten; /* Number of bytes read/written */
     char buf[NUM_BYTES];         /* Buffer to store part of file */

     /* Check usage */
     if (argc!=2)
     {
          /* We "cheat" a little, and use the buffered I/O routine fprintf
           * to print the error message if used improperly */
          fprintf(stderr,"Usage: %s file\n",argv[0]);
          exit (1);
     }

     /* Open input file */
     fd = open(argv[1], O_RDONLY);  

     if (fd == -1)                  /* check for error */
     {
          perror("Unable to open input file");
          exit (1);
     }
     
     /* Read from file */
     bytesRead = read(fd, buf, NUM_BYTES); /* Attempts to read NUM_BYTES */

     if (bytesRead == -1)           /* check for error */
     {
          perror("Unable to read file");
          exit (1);
     }

     /* Write to stdout */
     
     /* The file descriptor constant STDOUT_FILENO is defined in
      * fcntl.h and opened by the shell (or inherited from the parent
      * process) and corresponds to the "standard output" stdout. 
      */

      bytesWritten = write(STDOUT_FILENO, buf, bytesRead);

     if (bytesWritten != bytesRead)
     {
          perror("Write error");
          exit (1);
     }

     /* Close file */
     close(fd); 

     exit (0);
}
     
