Programming in C

(Barry) #1

360 Chapter 16 Input and Output Operations in C


displayed by printfdo not appear in your window but are instead written into the file
called data.
To see how this works, type in the very first program you wrote, Program 3.1, and
compile the program in the usual way. Now execute the program as you normally would
by typing in the program name (assume it’s called prog1):
prog1
If all goes well, you should get the output
Programming is fun.
displayed in your window. Now type in the following command:
prog1 > data
This time, notice that you did not get any output at the terminal.This is because the
output was redirected into the file called data. If you now examine the contents of the
file data,you should find that it contains the following line of text:
Programming is fun.
This verifies that the output from the program went into the file dataas described pre-
viously.You might want to try the preceding sequence of commands with a program that
produces more lines of output to verify that the preceding process works properly in
such cases.
You can do a similar type of redirection for the input to your programs. Any call to a
function that normally reads data from your window, such as scanfand getchar, can be
easily made to read its information from a file. Program 5.8 was designed to reverse the
digits of a number.The program uses scanfto read in the value of the number to be
reversed from the terminal.You can have the program instead get its input from a file
called number,for example, by redirecting the input to the program when the program is
executed. If the program is called reverse, the following command line should do the
trick:
reverse < number
If you type the number 2001 into a file called numberbefore issuing the preceding com-
mand, the following output appears at the terminal after this command is entered:
Enter your number.
1002
Notice that the program requested that a number be entered but did not wait for you to
type in a number.This is because the input to the program—but not its output—was
redirected to the file called number.Therefore, the scanfcall from the program had the
effect of reading the value from the file numberand not from your terminal window.The
information must be entered in the file the same way that it would be typed in from the
Free download pdf