C++的popen()
在执行一个进程后返回一个包含输出的文件描述符。而不是FILE *,我需要一个char *,即。一个字符串是我的输出。我该怎么办?请帮帮我。将C++ popen()的输出转换为字符串
回答
我想我会做一些事情这个一般顺序:
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;
为什么不使用'std :: string'作为最终结果并使用'append'? –
@KerrekSB:主要是因为我以某种方式认为它被标记为C而不是C++。 –
使用通常的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());
}
这将负责所有内存分配,并在完成后关闭流。
- 1. 将ReadProcessMemory输出转换为字符串
- 2. C#将字符串转换为字节并作为字符串输出
- 3. C#将Console.Writeline输出转换为电子邮件的字符串
- 4. C++奇怪的输出将字符串转换为int
- 5. 将Redis输出字符串转换为位字符串
- 6. Java:将Gzip字符串转换为输出字符串
- 7. C++ - 将字符串转换为字符
- 8. C将字符串/字符输入转换为浮点数
- 9. 如何将控制台输出的字符转换为字符串; C++
- 10. C#将字符串转换为数字
- 11. 从POPEN输出转换为数组
- 12. C:将atoi()的输出转换为无符号字符?
- 13. 如何将Objective-C字符串转换为C字符串?
- 14. 将字符串转换为位图c#
- 15. C#将字符串转换为uint
- 16. C++将char转换为字符串
- 17. C#将Unicode转换为字符串
- 18. c#将字符串转换为变量
- 19. 将字符串转换为日期C++
- 20. 将字符串转换为System.guid c#
- 21. 将字符串转换为int在C++
- 22. 将字符串转换为smtpclient在c#
- 23. 将字符串转换为总和C#
- 24. C++ ::将ASCII值转换为字符串
- 25. 将C#货币转换为字符串
- 26. C:将int []转换为字符串
- 27. C#,将字符串转换为DateTimeOffset
- 28. 将字符串转换为long long C?
- 29. 将float转换为字符串c
- 30. C#:将字符串转换为DBType.AnsiStringFixedLength
看一看此主题: http://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c 祝你好运! – DCMaxxx