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

The process is similar to reading from a file. We must declare a “file pointer” (we use out) and

associate it with the actual file (output.txt, say) using fopen. This can be done with

FILE * out = fopen("output.txt", "w");

This tells C to “open the file output.txt for writing”; "w" indicates writing. When this

statement is executed, the file output.txt is created if it does not already exist. If it exists, its

contents are destroyed. In other words, whatever you write to the file will replace its original

contents. Be careful that you do not open for writing a file whose contents you wish to keep.

5.9.1 fprintf

We use the statement (more precisely, the function) fprintf to send output to the file. It is

used in exactly the same way as printf except that the first argument is the file pointer out. For

example, if sum is int with value 143, the statement

fprintf(out, "The sum is %d\n", sum);

will write

The sum is 143

to the file output.txt.

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

When we have finished writing output to the file, we must close it. This is especially

important for output files since, the way some compilers operate, this is the only way to ensure

that all output is sent to the file. (For instance, they send output to a temporary buffer in memory;

only when the buffer is full is it sent to the file. If you do not close the file, some output may be left

in the buffer and never sent to the file.) We close the file with fclose, as follows:

fclose(out);

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

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

identifier out with another file (payroll.txt, say) using:

out = fopen("payroll.txt", "w");

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

declared as FILE *. Subsequent fprintf(out, ...) statements will send output to the file

payroll.txt.

For an example, we rewrite Program P5.6 as Program P5.7 by adding the fopen and fprintf

statements. The only difference is that P5.6 sends its output to the screen while P5.7 sends its

output to the file output.txt.

111

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!