0

I have a function provided by a library (so I can't edit the source code for it), that prints output to stdout. I wish to get that output in a string variable, so that I can check some conditions on it. What is the best way to do this? Can I do it without multithreading and file I/O?

[EDIT] Similar questions(pointed out in comments):

Using multithreading:

Capture Output of Spawned Process to string

If you know output size beforehand:

redirect output from stdout to a string?

Community
  • 1
  • 1
SPMP
  • 1,181
  • 1
  • 9
  • 24
  • Are you trying to do this internal to your program, or do you just want to capture it from the terminal for a bash script? – tonysdg Nov 13 '15 at 20:24
  • Internal to my program. – SPMP Nov 13 '15 at 20:25
  • 2
    You could redirect stdout to a file with something like this. http://stackoverflow.com/questions/14543443/in-c-how-do-you-redirect-stdin-stdout-stderr-to-files-when-making-an-execvp-or Definitely not the cleanest way but it would allow you to then open the file read it and compare. Should be able to jsut redirect to a pointer but I can't find that anywhere. – arduic Nov 13 '15 at 20:25
  • 2
    Did you try search stackoverflow first? This is duplicate of multiple. http://stackoverflow.com/questions/1162068/redirect-both-cout-and-stdout-to-a-string-in-c-for-unit-testing http://stackoverflow.com/questions/14715493/redirect-standard-error-to-a-string-in-c http://stackoverflow.com/questions/14428406/redirect-output-from-stdout-to-a-string http://stackoverflow.com/questions/11214498/capture-stdout-to-a-string-and-output-it-back-to-stdout-in-c etc... – fukanchik Nov 13 '15 at 20:28
  • 1
    You have a `C++` answer. Did you want a `C` answer too? – Weather Vane Nov 13 '15 at 20:29
  • I didn't find these. Should I delete the question? – SPMP Nov 13 '15 at 20:30
  • C++ is fine for me. If there's a C answer, it'd help others I guess.. – SPMP Nov 13 '15 at 20:31
  • 1
    The cleanest approach which would catch *everything* is via `pipe->dup2->fork` – fukanchik Nov 13 '15 at 20:32
  • You *might* be able to do this in straight C using `fmemopen()`, assuming the app & library output use the stdout `FILE *` stream, not directly using the file descriptor. – keithmo Nov 13 '15 at 20:38

1 Answers1

1

Use rdbuf.

std::stringstream stream;
auto * old = std::cout.rdbuf(stream.rdbuf());
CallFunction();
std::cout.rdbuf(old);
std::string value = stream.str();
V. Kravchenko
  • 1,859
  • 10
  • 12