Sams Teach Yourself C in 21 Days

(singke) #1
Using Disk Files 447

16


16: for (count = 0; count < 5; count++)
17: scanf(“%f”, &data[count]);
18:
19: /* Get the filename and open the file. First clear stdin */
20: /* of any extra characters. */
21:
22: clear_kb();
23:
24: puts(“Enter a name for the file.”);
25: gets(filename);
26:
27: if ( (fp = fopen(filename, “w”)) == NULL)
28: {
29: fprintf(stderr, “Error opening file %s.”, filename);
30: exit(1);
31: }
32:
33: /* Write the numerical data to the file and to stdout. */
34:
35: for (count = 0; count < 5; count++)
36: {
37: fprintf(fp, “\ndata[%d] = %f”, count, data[count]);
38: fprintf(stdout, “\ndata[%d] = %f”, count, data[count]);
39: }
40: fclose(fp);
41: printf(“\n”);
42: return 0;
43: }
44:
45: void clear_kb(void)
46: /* Clears stdin of any waiting characters. */
47: {
48: char junk[80];
49: gets(junk);
50: }

Enter 5 floating-point numerical values.
3.14159
9.99
1.50
3.
1000.0001
Enter a name for the file.
numbers.txt
data[0] = 3.141590
data[1] = 9.990000
data[2] = 1.500000
data[3] = 3.000000
data[4] = 1000.000122

LISTING16.2 continued

INPUT/
OUTPUT

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

Free download pdf