Stream Redirection. Newbies question

A

Alexander Baranov

Hi.
I work in Debian Linux GCC. I have a function, which opens a socket and
binds 'mystream' stream with this socket (by fdopen command). Then, while
being inside this function I want stdout be redirected to mystream. On
exiting the function I have to return stdout to ordinary stdout.
I did it like this:

Entering function
{
...
FILE* sos_stdout;
sos_stdout = stdout; //reserving stdout
stdout = mystream; //redirecting
....
doing something
....
stdout = sos_stdout; //returning stdout back
fclose(mystream); //closing my stream
.....
Exiting..
}

It works, but I still have a feeling that I do it in a wrong way. Please,
advise if it is really so.
Regards, Alex.
 
K

Kenneth Brody

Alexander Baranov wrote:
[...]
FILE* sos_stdout;
sos_stdout = stdout; //reserving stdout
stdout = mystream; //redirecting

This statement won't work on all platforms, as "stdout" may not be an
lvalue. For example, several of my systems have stdio.h lines like:

#define stdin (&__iob[0])
#define stdout (&__iob[1])
#define stderr (&__iob[2])

[...]

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <[email protected]>
 
D

Dan Pop

In said:
Entering function
{
..
FILE* sos_stdout;
sos_stdout = stdout; //reserving stdout
stdout = mystream; //redirecting
...
doing something
...
stdout = sos_stdout; //returning stdout back
fclose(mystream); //closing my stream
....
Exiting..
}

It works, but I still have a feeling that I do it in a wrong way. Please,
advise if it is really so.

You're right. stdin, stdout and stderr need not be modifiable lvalues,
so you may not be allowed to assign anything to them (even if it works
on your particular implementation).

Use fprintf on mystream instead of printf (ditto for fputs instead puts)
and you don't have to mess with stdout.

Dan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top