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

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

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

int main(int argc, char* argv[])
{
     FILE* fp;                    /* File stream pointer for reading file */
     int bytesRead, bytesWritten; /* Number of bytes read/written */
     char buf;                    /* Character read from file */

     /* Check usage */
     if (argc!=2)
     {
          fprintf(stderr,"Usage: %s file\n",argv[0]);
          exit (1);
     }

     /* Open input file */
     fp = fopen(argv[1], "r");

     if (fp == NULL) /* check for error */
     {
          perror("Unable to open input file");
          exit (1);
     }

     int i;
     for (i = 0 ; i<NUM_BYTES ; i++)
     {
          /* Read from file */
          buf = getc(fp);

          /* A return value of zero could mean nothing read (EOF) or an
           * error. We must use feof and/or ferror to distinguish these */
          if (ferror(fp))
          {
               perror("Unable to read file");
               exit (1);
          }

          /* Write to stdout */
          if (putc(buf,stdout) == EOF)
          {
               perror("Write error");
               exit (1);
          }
     }
     
     /* Close file */
     fclose(fp);

     exit (0);
}
