/********************************************************* * * redirect.c * * 4/16/02 Jeff Ondich * * This program illustrates the use of the dup2 function * to redirect the standard input and standard output. * Compile and run it in a directory that contains a * file named moose.txt. It will send its output to * a file named elk.txt. * * Note that I do not check the return value of close(), * since this is a very small program which won't change * its behavior even if the file closing fails, and since * all the files will get closed when the program terminates, * anyway. * *********************************************************/ #include #include #include #include #include #include #include int main() { char ch; int inputFD, outputFD; /* Open the input file for reading. */ inputFD = open( "moose.txt", O_RDONLY ); if( inputFD == -1 ) { perror( "Trouble opening moose.txt" ); exit( 1 ); } /* Attach the opened moose.txt to standard input. */ if( dup2( inputFD, STDIN_FILENO ) == -1 ) { perror( "Trouble with dup2 to stdin" ); close( inputFD ); exit( 1 ); } /* Close the inputFD file descriptor. Note that this leaves the duplicated file descriptor stdin open. */ close( inputFD ); /* Play the same open/dup2/close game with stdout. */ outputFD = open( "elk.txt", O_RDWR | O_CREAT, 0644 ); if( outputFD == -1 ) { perror( "Trouble opening elk.txt" ); exit( 1 ); } if( dup2( outputFD, STDOUT_FILENO ) == -1 ) { perror( "Trouble with dup2 to stdout" ); close( outputFD ); exit( 1 ); } close( outputFD ); /* Finally, read the contents of moose.txt via stdin and send them in uppercase form to elk.txt via stdout. */ while( (ch=getchar()) != EOF ) { putchar( toupper( ch ) ); } return 0; }