Sams Teach Yourself C in 21 Days

(singke) #1
Using Disk Files 449

16


LISTING16.3 fscanf.c. Using fscanf()to read formatted data from a disk
file
1: /* Reading formatted file data with fscanf(). */
2: #include <stdlib.h>
3: #include <stdio.h>
4:
5: int main( void )
6: {
7: float f1, f2, f3, f4, f5;
8: FILE *fp;
9:
10: if ( (fp = fopen(“INPUT.TXT”, “r”)) == NULL)
11: {
12: fprintf(stderr, “Error opening file.\n”);
13: exit(1);
14: }
15:
16: fscanf(fp, “%f %f %f %f %f”, &f1, &f2, &f3, &f4, &f5);
17: printf(“The values are %f, %f, %f, %f, and %f\n.”,
18: f1, f2, f3, f4, f5);
19:
20: fclose(fp);
21: return 0;
22: }

The values are 123.449997, 87.000999, 100.019997, 0.004560, and 1.000500

INPUT

OUTPUT

The precision of the values might cause some numbers to not display as the
Note exact values you entered. For example, 100.02might appear as 100.01999.

This program reads the five values from the file you created and then displays
them on-screen. The fopen()call on line 10 opens the file for read mode. It also
checks to see that the file opened correctly. If the file wasn’t opened, an error message is
displayed on line 12, and the program exits (line 13). Line 16 demonstrates the use of the
fscanf()function. With the exception of the first parameter,fscanf()is identical to
scanf(), which you have been using throughout this book. The first parameter points to
the file that you want the program to read. You can do further experiments with
fscanf(), creating input files with your programming editor and seeing how fscanf()
reads the data.

ANALYSIS

26 448201x-CH16 8/13/02 11:13 AM Page 449

Free download pdf