/***************************************************************************
 *  Columbia University Introduction to Computer Programming in C COMS 1003
 *  Cat a file
 *
 *  Copyright (C) 2005 Michael E. Locasto
 *
 *  All rights reserved.
 *
 * $Id: cat.c,v 1.1 2005/10/28 02:25:24 locasto Exp $
 **************************************************************************/

#include <stdio.h>
#include <errno.h>
#include <string.h>

extern int errno;


/**
 * This program simply dumps a file to stdout
 *
 * Note our added error handling. Note also that you can associate
 * different return values with different exit points of the program.
 *
 * For an alternative way to exit or halt execute, see the man pages
 * for the exit() function.
 * 
 */
int main(int argc, char* argv[])
{
   /* Declare a handle to a file. */
   FILE *fin = NULL;
   /* Declare a variable to hold the results of various calls. */
   int result = 0;
   /* Declare a variable to hold the result of reading input */
   int read_char = 0;

   /* open the named file for reading. */
   fin = fopen("hello.c", "r");
   /* test if the open operation failed for some reason */
   if(NULL==fin)
   {
      /* show the reason it failed and terminate. */
      fprintf(stderr, "error: %s\n",strerror(errno));
      perror("error opening file");
      fprintf(stderr,"error %d: could not open file\n", errno);
      return -1;
   }

   /* Read input while there is input to read. */
   while(EOF!=(read_char=fgetc(fin)))
   {
      /* Copy the input character to the stdout file stream */
      result = fputc(read_char,stdout);
      /* Check if the write operation suceeded */
      if(EOF==result)
      {
         /* If not, show some errors and terminate. */
         perror("error writing output");
         fprintf(stderr,"error %d: problem writing file to stdout\n", errno);
         /* Before terminating, close the input file, which is still OK
          * as far as we know...
          */
         result = fclose(fin);
         if(EOF==result)
         {
            perror("error closing file");
            fprintf(stderr,"error %d: problem closing file\n", errno);
            return -4;
         }
         return -2;
      }
   }

   /* Now that we are all done, close the file. */
   result = fclose(fin);
   if(EOF==result)
   {
      perror("error closing file");
      fprintf(stderr,"error %d: problem closing file\n", errno);
      return -3;
   }

   /* Return zero */
   return 0;
}
