Previous: 8.3.1 Character I/O
Up: 8.3 Direct I/O with Files
Previous Page: 8.3.1 Character I/O
Next Page: 8.4 Common Errors
When we read or write numeric data from or to standard file streams, scanf() and printf() convert character input to internal numeric values and vice versa. Similar functions are available for non-standard files. The function, fscanf() reads formatted input from a file and fprintf() writes formatted output to a file. The only difference between scanf(), printf() and fscanf(), fprintf() is that the latter require an additional argument which specifies the input file stream. For example, to read and write an integer from and to a file stream, we use:
fscanf(inp, "%d", &n);
fprintf(outp, "%d", n);
where inp and outp, are FILE pointers. The other arguments are
the same as those for scanf() and printf();
the format string gives the
conversion specifications, and the arguments that follow reference the objects
where data is to be stored or whose values are to be written.
The return value of fscanf() is
the same as scanf(): number of items read or EOF.
Our next task is to read exam scores into an array from a file and determine the average, the maximum, and the minimum. It is assumed that the data file of exam scores is prepared using an editor. The algorithm is simple enough:
get input file name
open input file
read exam scores into an array
process the array to find average, maximum, and minimum
We will use a function, proc_aray(),
to process the array. It will return the
average but will indirectly store the maximum and minimum values in the calling
function. The program is shown in Figure 8.8.
The sample session assumes that the scores are in an input file scores.dat prepared using an editor and shown below:
67 75 82 69Sample Session:
The function, proc_aray(), initializes values of local variables, max and min, to the value of the first element of the array, ex[0]. It then traverses the array, maintains a cumulative sum of the scores, and updates the values of max and min using the following conditional expressions:
max = ex[i] > max ? ex[i] : max;
min = ex[i] < min ? ex[i] : min;
Here,
if an array element, ex[i], is greater than max,
max is assigned ex[i];
otherwise, max is assigned max.
Similarly, the minimum is updated when an array
element is smaller than the minimum. Finally, the function indirectly stores
values of maximum and minimum, and returns the value of the average score.