Friday, November 4, 2011

Redirecting the Output in C programming

Let’s see how we can redirect the output of a program, from the screen to a file. We’ll start by considering the simple program shown below:

/* File name: util.c */
#include "stdio.h"<+>
main( )
{
char ch ;
while ( ( ch = getc ( stdin ) ) != EOF )
putc ( ch, stdout ) ;
}
/* File name: ascii.c*/
main( )
{
int ch ;
for ( ch = 0 ; ch <= 255 ; ch++ )
printf ( "\n%d %c", ch, ch ) ;
}

When this program is compiled and then executed at command prompt using the redirection operator,
C>ASCII.EXE > TABLE.TXT
the output is written to the file. This can be a useful capability any time you want to capture the output in a file, rather than displaying it on the screen.
DOS predefines a number of filenames for its own use. One of these names in PRN, which stands for the printer. Output can be redirected to the printer by using this filename. For example, if you invoke the “ascii.exe” program this way:
C>ASCII.EXE > PRN
the ASCII table will be printed on the printer.
On compiling this program we would get an executable file UTIL.EXE. Normally, when we execute this file, the putc( ) function will cause whatever we type to be printed on screen, until we don’t type Ctrl-Z, at which point the program will terminate, as
shown in the following sample run. The Ctrl-Z character is often called end of file character.

C>UTIL.EXE
perhaps I had a wicked childhood,
perhaps I had a miserable youth,
but somewhere in my wicked miserable past,
there must have been a moment of truth ^Z
C>

Now let’s see what happens when we invoke this program from in a different way, using redirection:

C>UTIL.EXE > POEM.TXT
C>

Here we are causing the output to be redirected to the file POEM.TXT. Can we prove that this the output has indeed gone to the file POEM.TXT? Yes, by using the TYPE command as follows:

C>TYPE POEM.TXT
perhaps I had a wicked childhood,
perhaps I had a miserable youth,
but somewhere in my wicked miserable past,
there must have been a moment of truth
C>

There’s the result of our typing sitting in the file. The redirection operator, ‘>’, causes any output intended for the screen to be written to the file whose name follows the operator.
Note that the data to be redirected to a file doesn’t need to be typed by a user at the keyboard; the program itself can generate it. Any output normally sent to the screen can be redirected to a disk file. As an example consider the following program for generating the ASCII table on screen:

No comments:

Post a Comment