08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 5 ■ Programs with Repetition Logic

We can tell C we will be reading data from the file with this:

FILE * in = fopen("C:\\testdata\\input.txt", "r");

Recall that the escape sequence \\ is used to represent \ within a string. If the file is on a flash

drive with assigned letter E, we can use:

FILE * in = fopen("E:\\input.txt", "r");

5.8.1 fscanf

We use the statement (more precisely, the function) fscanf to read data from the file. It is used

in exactly the same way as scanf except that the first argument is the file pointer in. For example,

if num is int, the statement

fscanf(in, "%d", &num);

will read an integer from the file input.txt (the one associated with in) and store it in num. Note

that the first argument is the file pointer and not the name of the file.

When we have finished reading data from the file, we should close it. This is done with

fclose, as follows:

fclose(in);

There is one argument, the file pointer (not the name of the file). This statement breaks the

association of the file pointer in with the file input.txt. If we need to, we could now link the

identifier in with another file (paydata.txt, say) using:

in = fopen("paydata.txt", "r");

Note that we do not repeat the FILE * part of the declaration, since it has already been

declared as FILE *. Subsequent fscanf(in, ...) statements will read data from the file

paydata.txt.

5.8.2 Find Average of Numbers in a File

To illustrate the use of fscanf, let us rewrite Program P5.3 to read several numbers from a file and

find their average. Previously, we discussed how to find the average. We just need to make the

changes to read the numbers from a file. Suppose the file is called input.txt and contains several

positive integers with 0 indicating the end, for example,

24 13 55 32 19 0

Program P5.6 shows how to define the file as the place from which the data will be read and how

to find the average.

108

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!