• C

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 );
printf("to file");
printf("to stdout");

Open in new window

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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");

int d;
int redir = open("name", O_WRONLY );

printf("to file");
 printf("to stdout");

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day 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()
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.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.