Sunday, January 10, 2010

10.3 READING AND WRITING A DATA FILE

Files are generally  used for two purposes- reading and writing. Whenever we want to store something into a file, the file needs to be opened in write mode. If the contents to be stored in the output file are already known then the then the file can also be created directly using a text editor or word processor. In that case the file is obviously a formatted stream-oriented data file. However, if the contents to be stored are not pre-defined and are computed generated with the help of a program itself. then the output file can be created with help of a program only.

The following program reads all the numbers from the input file values.dat and stores average of these numbers in an output file named as average.res

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


main()
{
FILE *fpin, *fpout;
float val, avg, sum=0;
int count=0;


if ((fpin = fopen("values.dat", "r"))== NULL)
   /*open the data file for reading purposes*/
  printf("\nERROR - cannot open the designated file\n");

else  {/*read and display each character from the file*/
   while(!feof(fpin))  {
fscanf(fpin, "%f", &val);
sum += val;
count++;

}
}
avg = sum/count;
if ((fpout = fopen("average.res", "w")) == NULL)
   /*open the data file for writing purposes*/
  printf("\nERROR- cannot open the designated file\n");
else  /*write the average in the file*/
  fprintf(fpout, "The average of numbers of file values.dat is %.3f\n", avg);


fclose(fpin);
fclose(fout);
getch();


}

If the average value computed is 81.563, then the output line will have the following line

The average of numbers of file values.dat is 81.563

No comments:

Post a Comment