• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 259
  • Last Modified:

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

0
btocakci
Asked:
btocakci
  • 4
1 Solution
 
97WideGlideCommented:
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");

0
 
ozoCommented:
int d;
int redir = open("name", O_WRONLY );
 d=dup(fileno(stdout));
 fflush(stdout);

dup2(redir,fileno(stdout));
printf("to file");
 fflush(stdout);
close(redir);
dup2(d,fileno(stdout));
 printf("to stdout");
 fflush(stdout);

0
 
97WideGlideCommented:
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.
0
 
97WideGlideCommented:
didn't C the close(1);
0
 
97WideGlideCommented:
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.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now