简体   繁体   English

将FILE * stdout重定向到C ++中的字符串

[英]Redirect FILE * stdout to string in c++

I want to execute some function of C in C++. 我想在C ++中执行C的某些功能。 The function takes FILE * as argument: 该函数将FILE *作为参数:

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? 但是如何使此函数在c ++中打印到流或字符串流,处理结果呢? 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. 在Linux中,最好的选择是匿名管道。

First, create a pipe: 首先,创建一个管道:

int redirectPipe[2];
pipe(redirectPipe)

Then, open the file descriptor returned to us via pipe(2) using fdopen: 然后,使用fdopen打开通过pipe(2)返回给我们的文件描述符:

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. 然后,像使用常规文件一样使用outHandle读取。

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. 要注意的一件事:管道具有固定的缓冲区大小,如果有可能使getInfo函数填充缓冲区,则将出现死锁。

To prevent the deadlock, you can either call getInfo from another thread, or increase pipe buffer size using fcntl and F_SETPIPE_SZ . 为了防止死锁,您可以从另一个线程调用getInfo ,或者使用fcntlF_SETPIPE_SZ增加管道缓冲区的大小。 Or better, as Ben Voigt mentioned in the comments, create a temp file. 或者更好,如Ben Voigt在评论中提到的,创建一个临时文件。

Note: I was specific to *nix since OP mentioned he/she wanted the "best one in linux" 注意:我是特定于* nix的,因为OP提到他/她想要“ Linux上最好的”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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