L-36 MCS 275 Mon 9 Apr 2001

Below is the program we discussed in class.
/* L-36 MCS 275 Mon 9 Apr 2001 : writing a file backward */

/* The program below is taken from Al Kelley and Ira Pohl,
   "C by Dissection.  The essentials of C programming",
   3rd Edition, 6th Printing 1998, page 481.
   It illustrates the random access to files and the
   use of stderr to ensure proper working with redirection,
   i.e., when you call the program like a.out > output.
   The problem with the code in the book is that ftell(ifp)
   never becomes negative with the gcc compiler on Linux,
   so the stop condition in the while loop has to be changed.
   Also the SUN executable cycles in an infinite loop with
   the code from the book.  The version below works fine.  */

#include <stdio.h>

#define MAX 100

int main()
{
   char  filename[MAX];
   int   c;
   FILE  *ifp;

   fprintf(stderr,"\nGive a file name for input : ");
   scanf("%s", filename);
   ifp = fopen(filename,"rb");   /* ms-dos binary mode */
   fseek(ifp,0,2);               /* move to end of file */
   fseek(ifp,-1,1);              /* back one character */
   while (ftell(ifp) > 0)        /* ftell(ifp) == 0 : at start of ifp */
   {
      c = getc(ifp);             /* unformatted input of character */
      putchar(c);                /* write character to output */
      fseek(ifp,-2,1);           /* back two characters */
   }
   c = getc(ifp);                /* get first character on file */
   putchar(c);                   /* write first character to output */
   return 0;
}