Programming in C

(Barry) #1
Input and Output Operations with Files 359

The newline character is repeated outside the brackets so that scanfmatches it and does
not read it the next time it’s called. (Remember,scanfalways continues reading from
the character that terminated its last call.)
When a value is read that does not match a value expected by scanf(for example,
typing in the character xwhen an integer is expected),scanfdoes not read any further
items from the input and immediately returns. Because the function returns the number
of items that were successfully read and assigned to variables in your program, this value
can be tested to determine if any errors occurred on the input. For example, the call
if ( scanf ("%i %f %i", &i, &f, &l) != 3 )
printf ("Error on input\n");
tests to make certain that scanfsuccessfully read and assigned three values. If not, an
appropriate message is displayed.
Remember, the return value from scanfindicates the number of values read and
assigned, so the call
scanf ("%i %*d %i", &i1, &i3)
returns 2 when successful and not 3 because you are reading and assigning twointegers
(skipping one in between). Note also that the use of %n(to obtain the number of charac-
ters read so far) does not get included in the value returned by scanf.
Experiment with the various formatting options provided by the scanffunction. As
with the printffunction, a good understanding of these various formats can be
obtained only by trying them in actual program examples.

Input and Output Operations with Files


So far, when a call was made to the scanffunction by one of the programs in this book,
the data that was requested by the call was always read in from your terminal. Similarly,
all calls to the printffunction resulted in the display of the desired information in your
terminal window. In this section, you learn how you can read and write data from and
to a file instead.

Redirecting I/O to a File


Both read and write file operations can be easily performed under many operating
systems, such as Unix and Windows, without anything special being done at all to the
program. If you want to write all your program results into a file called data,for exam-
ple, all that you need to do under Unix or Windows if running in a terminal window is
to redirect the output from the program into the file databy executing the program
with the following command:
prog > data
This command instructs the system to execute the program progbut to redirect the out-
put normally written to the terminal into a file called datainstead. So, any values

TEAM FLY

Free download pdf