C++ popen() 的输出到字符串
C++ popen()'s output to a string
C++的popen()
在执行进程后返回包含输出的文件描述符。我需要一个字符*,而不是文件*,即。一个字符串作为我的输出。我该怎么办?请帮助我。
我想
我会按照这个一般顺序做点什么:
char big_buffer[BIG_SIZE];
char small_buffer[LINE_SIZE];
unsigned used = 0;
big_buffer[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());
}
这将处理所有内存分配,并在完成流后再次关闭流。
相关文章:
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何从void函数输出字符串
- 输出字符串数组
- 如何输出字符串第二个单词的第一个字母?
- 多线程环境中的输出字符串流出现问题
- 输出字符串到cmd显示的右显示,但未被认为是命令
- 读取文本文件并输出字符串
- 输出字符串使用 C++ 覆盖 Linux 终端上的最后一个字符串
- 如何在C++中输出字符串的向量
- 无法从类模板输出字符串
- FWRITE 输出字符串不正确
- Qt单元测试输出字符串长度截止
- 无法显示输出字符串
- 如果条目大于90,则输出字符串的布尔函数
- C++不带 'n' 或 endl 的输出字符串将在字符串末尾输出'#'
- 在C++中输出字符串和 strncpy 时遇到问题
- 获取c#输出字符串参数值为c++ BSTR*
- C++初学者,开关不输出字符串的第一个字符
- 输出字符串/字符错误(c++)
- Getline()省略输出字符串的第一个字母