简体   繁体   中英

Redirect FILE * stdout to string in c++

I want to execute some function of C in C++. The function takes FILE * as argument:

void getInfo(FILE* buff, int secondArgument);

You can make it to print to stdout:

getInfo(stdout, 1);
// the function prints results into stdout, results for each value secondArgument

But how to make this function to print to stream or stringstream in c++, process the results? I want to capture what the function prints, into a string, and do some processing on the resulting string.

I try something like this:

for (i=0; i<1000; i++) {
  getInfo(stdout, i);
  // but dont want print to stdout. I want capture for each i, the ouput to some string
  // or array of strings for each i.
}

In linux, your best bet is anonymous pipe.

First, create a pipe:

int redirectPipe[2];
pipe(redirectPipe)

Then, open the file descriptor returned to us via pipe(2) using fdopen:

FILE* inHandle = fdopen(redirectPipe[0], "w");
FILE* outHandle = fdopen(redirectPipe[1], "r");

Call the function:

getInfo(inHandle, someValue);

Then, read using outHandle as if it's a regular file.

One thing to be careful: Pipes have fixed buffer size and if there is a possibility for getInfo function to fill the buffer, you'll have a deadlock.

To prevent the deadlock, you can either call getInfo from another thread, or increase pipe buffer size using fcntl and F_SETPIPE_SZ . Or better, as Ben Voigt mentioned in the comments, create a temp file.

Note: I was specific to *nix since OP mentioned he/she wanted the "best one in linux"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM