Link to home
Start Free TrialLog in
Avatar of btocakci
btocakciFlag for Türkiye

asked on

redirecting input and output

H0! I want to redirect output to a file and then direct to stdout again.

My aim is to print the first statement to file and the second to the stdout.  But they both are printed to file. How to correct this? And can you summarize shortly that when i fork a new process, the file descriptor passes to the new process as i changed or the default descriptor is passed to the new process? Thanks in advance.
redir = open(name, O_WRONLY );
close(1);
dup(redir);
printf("to file");
close(redir);
printf("to stdout");

Open in new window

Avatar of 97WideGlide
97WideGlide

I would use fprintf and printf :


FILE * filePtr;

filePtr  = fopen (name, "wt");        /* "wt" means the file is a write only text file */

printf (           "to stdout\n");
fprintf(filePtr, "to file\n");

ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
BTW, I am surprised that both are going to a file instead of the console.  I would swear that both lines would print to stdout.
didn't C the close(1);
For some reason, I've always thought to use :

read() and write() with open()
     AND
printf() and fprintf() with fopen();


Not sure if it was just personal preference, or if it was actually better or if it didn't matter.  Feel free to comment.