Monday, May 12, 2008

I/O Redirection:

Normally a C program takes its input from the keyboard (standard input device) and sends its output to the screen or terminal ( standard output device) But in cases where we would like to take input or output from other sources (other than the standard devices) we use what is known as redirection . The redirection operators are ">" for output , "<" for input



/* File name is test1.c */

#include

#include

main( )

{

char ch ;

printf(“\n Enter ^z to terminate input”);

while ( (ch = getchar() ) != EOF)

putchar(ch );

getch();

}

This program takes input from keyboard and prints it on screen . Suppose the exe file generated by this source code is test1.exe then the output of this program can be redirected at the DOS prompt as

C:>test2.exe > trytest2.txt

Here the output of test1.exe instead of being printed on screen is redirected to another file trytest1.txt .

This file can then be read at DOS prompt by the dos command type C:>type trytest2.txt

This will print the contents of the file on screen .

C:>test2.exe > PRN

This command will accept text from the keyboard and redirect the output of test2.exe to the printer .

Suppose we have a file called Sample.txt containing the following text “There is no limit to what can be accomplished if it does not matter matter who gets the credit”

We can take input from this file using redirection at the DOS prompt as

C:>test.exe < text.c

In this case the contents of the file Text.c will be printed on the screen without us doing anything or giving any input from the keyboard.

No comments: