[prog] C programming - capturing information sent to stdout

Sue Stones suzo at spin.net.au
Wed Jul 13 08:59:16 EST 2005


Kathryn Hogg wrote:

> To specifically answer your question, the canonical way of redirecting
>
>stdout is to first open a file where you want it to go.  You can either
>use open() if you want it to go to a file or perhaps call pipe() if you
>want to avoid an intermediate file.  Then you need to close stdout (fd 1):
>
>   close(1);
>  
>
Thanks Kathryn, apparently this doesn't work on all systems, I need 
portable code. freopen() does the close then open.  Then I needed to 
find a way to restore stdout, I did this by forking a new process and 
only redirecting stdout in the new process.  I was starting to 
investigate pipes, but since this worked I stooped there.  If this is 
bad style I would like to know.

>and then dup() the file opened above and then close it.:
>
>   int fd = open(.....);
>   close(1);
>   int newfd = dup(fd);
>   assert(newfd == 1);
>   close(fd);
>   // now do your code that writes to stdout
>
>
>  
>
I don't understand why there is a need to dup(fp).  What does it achieve 
that fd = open(.....) doesn't?

The assert is a new thing to me, so I read up on it of course.  Are 
there stylistic boundaries on when and where it should be used?

>I don't know jack about libcurl but it should provide you a mechanism to
>redirect the output.  A quick scan of the libcurl documention (
>http://curl.haxx.se/libcurl/c/libcurl-tutorial.html) has this to say:
>
><...>
>
> curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, write_data);
>  
>
<....>

I did look here first.  Perhaps I was missing something but I couldn't 
get this to write the actual webpage to a file.  It seems to work for 
downloading files in the ftp sense, and for saving data such as the 
number of files (metadata really) but not for the actual HTML that is 
returned.

sue







More information about the Programming mailing list