/* 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[NUM_BYTES];         /* 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);
     }

     /* Read from file */
     bytesRead = fread(buf, 1 /* byte */, NUM_BYTES, 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 */
     bytesWritten = fwrite(buf, 1 /* byte */, NUM_BYTES, stdout );

     if (bytesWritten < bytesRead || ferror(stdout))
     {
       perror("Write error");
       exit (1);
     }
     
     /* Close file */
     fclose(fp);

     exit (0);
}
