View Full Version : help with redirecting std output & errors

04-16-2002, 11:49 AM
hi all,
i am currently stuck on a project and would appriciate any help.

i have to write a spawn program which accepts info from the command line and then sorts out the arguments.

if -o is an argument then the following arg is the filename where the o/p is sent.

if -e is present the the next arg is the file name where the errors are sent.


$ spawn [-o filename] [-e filename] command_sequence

$ ./spawn -o list.dat ls -l /home/jbloggs

[New list.dat file contains long listing of the jbloggs directory.]

any ideas?

04-16-2002, 12:09 PM
This sounds like an excercise in the use of freopen(). Here is the prototype:
FILE *freopen (const char *path, const char *mode, FILE *stream);freopen() is often used to redirect stdout and stderr. Here is an example:

#include <errno.h>
#include <stdio.h>

int main( void )
FILE *NewStdout;
FILE *NewStderr;

NewStdout = freopen( "outfile", "w", stdout );
if ( !NewStdout )
perror( "freopen()" );
return (errno);

NewStderr = freopen( "errfile", "w", stderr );
if ( !NewStderr )
perror( "freopen()" );
return (errno);

printf( "Testing stdout redirection\n" );
perror( "Testing stderr redirection" );

fclose( NewStdout );
fclose( NewStderr );

return 0;

04-22-2002, 07:09 AM
in the above program how would you change it to take the argument from the command line.

04-22-2002, 02:59 PM
Hi Fergie,

I don't want to give it all away, as this seems to be a homework assignment, but here are a few hints:

The first argument of freopen() is the destination for the redirected output.
main() can accept the arguments int argc and char **argv (sometimes this is written as: char *argv[]).
[/list=1]As your instructor expects you to be able to write a program that uses argc and argv, I'm sure it has been covered in your class. Review your notes on how to pass arguments from the command line and, if you get stuck, reply with some specific questions.

I'd like to see you complete your assignment, but I also don't want to deprive you of the learning process. :)