Reading from a Text File


C Class,

The following routine shows how to read from a file.  

The routine does a bit more.  It shows a very simple technique for both 
reading from a file and also writing to a file.  Take some time to understand 
it and you will save yourself many painful hours.

This file is also on my home page.

In addition, it is available on the PC against the wall that is normally used 
to measure temperature as;

    c:\c_class\fileread.c

[At least, it will be when i get in on Monday]

A reminder.  A special lecture at 7:00 on Monday in the Digital Lab.  See you 
there!

Have a good day.

*********


/* FILE F_READ.C
**
** Illustrates how to read from a file
**
** Assumes there is an ASCII file named test.in on the a:
** drive.
**
** test.in consists of the following;
**
** P    5.0 36.7
** R    3.0 -4.0
**
** Output is displayed on terminal and written to a file.
**
** P. H. Anderson, MSU, March 4, '96
**
*/

#include <conio.h>
#include <stdio.h>

FILE *fo, *fi;  /* note there is an out and in file */

void wrt(char *s);

main()
{
   float x, y;
   char ch, s[80];
   int n;

   /* first, open the files */
   fi = fopen("a:\\test.in", "rt");  /* note r as in read */
   if(fi == NULL)
   {
    printf("Unable to open input file!\n");
    fcloseall();  /* close any open files */
     exit(-1);
   }
   fo = fopen("a:\\test.out", "wt");
   if(fo == NULL)
   {
    printf("Unable to open output file!\n");
    fcloseall();
     exit(-1);
   }

   for (n=0; n<2; n++)
   {
     fgets(s, 80, fi);  /* get a whole line from the file */
     wrt("Read as Input: ");
     wrt(s);   /* and write it to the output file */
     wrt("\n");
     /* now sscanf from the string */
     sscanf(s, "%c %f %f", &ch, &x, &y);
     /* now do what you want to do */
     /* in my case, i simply printed */

     if (toupper(ch) == 'P')
     {
        sprintf(s, "Polar:  %f/_%f\n", x, y);
        wrt("Output: ");
        wrt(s);
     }

     else if (toupper(ch) == 'R')
     {
        sprintf(s, "Rectangular:  %f+j%f\n", x, y);
        wrt("Output: ");
        wrt(s);
     }
     else
     {
        sprintf(s, "Invalid\n");
        wrt("Output: ");
        wrt(s);
     }
   }
   fcloseall();
}

void wrt(char *s) /* writes string s to terminal and to file */
{
   printf("%s", s);
   fprintf(fo, "%s", s);
}