[prog] C programming - capturing information sent to stdout

Kathryn Hogg kjh at flyballdogs.com
Wed Jul 13 05:00:32 EST 2005


Sue Stones said:
> I am trying to work out how to capture data sent to stdout for use
> elsewhere in the program.
>
> Using libcurl I query a webpage, HTML code is returned and sent to
> stdout.  But I need to somehow capture this output and processes it to
> retrieve the data that I need.  What is the best way to do this?  So far
> I haven't found anything that works, but its some years since I did any
> C programming and I am a little rusty.  Any help would be most useful.

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

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 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:

Let's assume for a while that you want to receive data as the URL
identifies a remote resource you want to get here. Since you write a sort
of application that needs this transfer, I assume that you would like to
get the data passed to you directly instead of simply getting it passed to
stdout. So, you write your own function that matches this prototype:

 size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp);

You tell libcurl to pass all data to this function by issuing a function
similar to this:

 curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, write_data);

You can control what data your function get in the forth argument by
setting another property:

 curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &internal_struct);

Using that property, you can easily pass local data between your
application and the function that gets invoked by libcurl. libcurl itself
won't touch the data you pass with CURLOPT_WRITEDATA.

libcurl offers its own default internal callback that'll take care of the
data if you don't set the callback with CURLOPT_WRITEFUNCTION. It will
then simply output the received data to stdout. You can have the default
callback write the data to a different file handle by passing a 'FILE *'
to a file opened for writing with the CURLOPT_WRITEDATA option.

-- 
Kathryn
http://womensfooty.com



More information about the Programming mailing list