Writing to a File


/*
** File FILE_1.C
**
** Illustrates how to write to a file.
**
** Calculates natural log of numbers between points entered by user.
** output is written to crt using printf and to file out.lis
** using fprintf.
**
** Note that the specific lines used to accomplish this are
** identified thus;  /*****1*****//* and the following explanation
** is keyed to these numbers.
**
**  1.  fprintf is defined in 
**  2.  pointer to a file declared.  You need not understand.
**
**  3.  file named out.lis opened at beginning of program.
**      all subsequent fprintf is written to this file.
**  4.  printf still directs to the crt.  fprintf of very
**      similar structure directs to the file.
**  5.  file must be closed prior to exiting the routine.
**
** Peter H. Anderson, 2 Feb, 97
*/

#include <stdio.h>   /****1****/
#include <process.h> /* for system command */
#include <conio.h>  /* for clrscr */
#include <dos.h> /* for delay */
#include <math.h>

FILE *f1;            /****2****/

main()

{
   int n;
   float x, y, start_point, end_point;
   clrscr();

   f1 = fopen ("out.lis", "wt");  /****3****/
   /* out.lis is the name of the file */
   /* "wt" means the file is a write only text file */

   printf ("Enter Start and End Points: ");
   scanf ("%f %f", &start_point, &end_point);
   /* should have error checking for negative numbers, zero and
   that end_point > start point */


   for (n = 0; n<20; ++n)
   {
	 x = start_point + (end_point - start_point) *n/20;
	 y = (float) log ((float) x); /* note type cast */
         printf ("%f\t%f\n", x, y);
         fprintf (f1, "%f\t%f\n", x, y);  /****4****/
   }  /*of for*/


   fclose (f1);  /****5*****/

   delay(1000);
   clrscr();

   system("type out.lis"); /* list the file to the screen */
   /* illustrates the system command */

} /*of main*/

/*
Note that the form of the fprintf is the same as the printf,
with one exception, the fprintf includes a destination;

	fprintf (f1, ".........");

*/