Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

file dup'ing

13 views
Skip to first unread message

sinbad

unread,
Oct 29, 2012, 3:54:40 AM10/29/12
to
how to redirect stdout to a user specified file.
and how do i redirect back from the user file to
stdout. i tried with dup() and dup2(), notthing
seems to be working, can anyone shed some light
on this and any pitfalls that one should take care
during the course of dup'ing.

Nicolas George

unread,
Oct 29, 2012, 4:19:11 AM10/29/12
to
sinbad , dans le message
<871a5118-9fe8-411b...@googlegroups.com>, a écrit :
> and how do i redirect back from the user file to
> stdout.

When?

> i tried with dup() and dup2(),

Show your code.

> notthing
> seems to be working

This is not accurate enough.

Xavier Roche

unread,
Oct 29, 2012, 4:20:58 AM10/29/12
to
On 10/29/2012 08:54 AM, sinbad wrote:
> how to redirect stdout to a user specified file.
> and how do i redirect back from the user file to
> stdout.

Just copy the standard output fd first using dup().

Eg.:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char **argv) {
const int old_stdout = dup(1);
FILE *fp = fopen("/tmp/stdout.out", "wb");

printf("Hello, this is printed on standard output\n");

if (fp != NULL) {
const int fp_fd = fileno(fp);

if (dup2(fp_fd, 1) == -1) {
perror("dup2");
}

printf("Hello, this is printed on a file\n");

if (dup2(old_stdout, 1) == -1) {
perror("dup2");
}

printf("Hello, this is printed on standard output again\n");

}

return 0;
}


Nobody

unread,
Oct 29, 2012, 3:57:38 PM10/29/12
to
On Mon, 29 Oct 2012 09:20:58 +0100, Xavier Roche wrote:

> On 10/29/2012 08:54 AM, sinbad wrote:
>> how to redirect stdout to a user specified file. and how do i redirect
>> back from the user file to stdout.
>
> Just copy the standard output fd first using dup().

Don't forget to fflush() the stream before calling dup2().

For input streams, the situation is more complex. fflush() may discard
buffered data, but that's an implementation-specific extension. In any
case, the underlying file position will be after any buffered data.

Nicolas George

unread,
Oct 29, 2012, 4:22:03 PM10/29/12
to
Nobody , dans le message <pan.2012.10.29....@nowhere.com>, a
écrit :
> Don't forget to fflush() the stream before calling dup2().
>
> For input streams, the situation is more complex. fflush() may discard
> buffered data, but that's an implementation-specific extension. In any
> case, the underlying file position will be after any buffered data.

Mixing stdio with low level fd manipulation is a bad idea to start with.

Joe Pfeiffer

unread,
Oct 29, 2012, 6:45:56 PM10/29/12
to
You may want to look at the freopen() or fdopen() calls.
0 new messages