[英]C++ popen()'s output to a string
在執行進程后,C ++的popen()
返回包含輸出的文件描述符。 而不是FILE *,我需要一個char *,即。 一個字符串作為我的輸出。 我該怎么辦? 請幫我。
我想我會對這個一般訂單做點什么:
char big_buffer[BIG_SIZE];
char small_buffer[LINE_SIZE];
unsigned used = 0;
big_buffer[0] = '\0'; // initialize the big buffer to an empty string
// read a line data from the child program
while (fgets(small_buffer, LINE_SIZE, your_pipe)) {
// check that it'll fit:
size_t len = strlen(small_buffer);
if (used + len >= BIG_SIZE)
break;
// and add it to the big buffer if it fits
strcat(big_buffer, small_buffer);
used += strlen(small_buffer);
}
如果您想要更精細,可以動態分配空間,並嘗試根據需要增加空間以保持您獲得的輸出量。 這將是一條更好的路線,除非你至少知道孩子可能產生多少輸出。
編輯:鑒於您使用的是C ++,動態大小的結果實際上非常簡單:
char line[line_size];
std::string result;
while (fgets(line, line_size, your_pipe))
result += line;
使用通常的stdio
例程將FILE*
的輸出讀入字符串。
請參閱https://stackoverflow.com/a/10702464/981959
你可以用兩行代碼(三個包括一個typedef來提高可讀性):
#include <pstream.h>
#include <string>
#include <iterator>
int main()
{
redi::ipstream proc("./some_command");
typedef std::istreambuf_iterator<char> iter;
std::string output(iter(proc.rdbuf()), iter());
}
這將完成所有內存分配並在您完成后再次關閉流。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.