redirect stdout/stderr to a string
Yes, you can redirect it to an std::stringstream
:
std::stringstream buffer;
std::streambuf * old = std::cout.rdbuf(buffer.rdbuf());
std::cout << "Bla" << std::endl;
std::string text = buffer.str(); // text will now contain "Bla\n"
You can use a simple guard class to make sure the buffer is always reset:
struct cout_redirect {
cout_redirect( std::streambuf * new_buffer )
: old( std::cout.rdbuf( new_buffer ) )
{ }
~cout_redirect( ) {
std::cout.rdbuf( old );
}
private:
std::streambuf * old;
};
redirect output of an function printing to console to string
Yes. That can be done. Here is a little demo:
#include <sstream>
#include <iostream>
void print_to_console() {
std::cout << "Hello from print_to_console()" << std::endl;
}
void foo(){
std::cout<<"hello world"<<std::endl;
print_to_console(); // this could be printed from anything
}
int main()
{
std::stringstream ss;
//change the underlying buffer and save the old buffer
auto old_buf = std::cout.rdbuf(ss.rdbuf());
foo(); //all the std::cout goes to ss
std::cout.rdbuf(old_buf); //reset
std::cout << "<redirected-output>\n"
<< ss.str()
<< "</redirected-output>" << std::endl;
}
Output:
<redirected-output>
hello world
Hello from print_to_console()
</redirected-output>
See Online Demo.
Redirecting stderr to stdout using string stream
This is because you do not restore the buffer of cerr
before your program exits. Do it like this:
#include <iostream>
#include <sstream>
int main()
{
std::stringstream oss;
std::streambuf* old = std::cerr.rdbuf( oss.rdbuf() );
std::cerr << "this goes to cerr";
std::cout << "[" << oss.str() << "]";
std::cerr.rdbuf(old);
}
See this answer of mine for a solution that is exception safe.
Can I redirect the stdout into some sort of string buffer?
from cStringIO import StringIO # Python3 use: from io import StringIO
import sys
old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()
# blah blah lots of code ...
sys.stdout = old_stdout
# examine mystdout.getvalue()
How to redirect STDOUT and STDERR to a variable
Are you seeking to capture the output in a variable? If so, you have use backticks or qx{}
with appropriate redirection. For example, you could use:
#/usr/bin/env perl
use strict;
use warnings;
# Ensure we have a way to write messages
open my $fh, '>', "output" or die;
close(STDOUT);
close(STDERR);
my $out;
open(STDOUT, ">>", \$out) or do { print $fh, "failed to open STDOUT ($!)\n"; die };
open(STDERR, ">>", \$out) or do { print $fh, "failed to open STDERR ($!)\n"; die };
foreach my $i (1..10)
{
print "print $i\n";
warn "warn $i\n";
my $extra = qx{make pth$i 2>&1};
print $fh "<<$i>><<$out>><<$extra>>\n";
}
(I happen to have programs pth1, pth2 and pth3 in the directory - they were made OK; pth4 and above write errors to stderr; the redirection was necessary.)
You should always check the success of operations such as open()
.
Why is this necessary? Because writing to a variable requires the cooperation of the process doing the writing - and make
doesn't know how to cooperate.
Redirect stdout to a string in Java
Yes - you can use a ByteArrayOutputStream
:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.setOut(new PrintStream(baos));
Then you can get the string with baos.toString()
.
To specify encoding (and not rely on the one defined by the platform), use the PrintStream(stream, autoFlush, encoding)
constructor, and baos.toString(encoding)
If you want to revert back to the original stream, use:
System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
How to redirect and append both standard output and standard error to a file with Bash
cmd >>file.txt 2>&1
Bash executes the redirects from left to right as follows:
>>file.txt
: Openfile.txt
in append mode and redirectstdout
there.2>&1
: Redirectstderr
to "wherestdout
is currently going". In this case, that is a file opened in append mode. In other words, the&1
reuses the file descriptor whichstdout
currently uses.
Related Topics
Error , Symbol 'Vector' Could Not Be Resolved
System("Command") Produces an Error; But It Works When Invoked Directly from Bash Prompt
How to Make Transparent Window on Linux
Problems Cross Compiling Qt 4.7 from Source for Arm
How to Measure CPU Time of a Specific Set of Threads
Why Is Padding Added for Multiple Data Members of Structures and Not for Single Members
About the Binary Compatibility of Linux
Single Process Maximum Possible Memory in X64 Linux
Create Window Without Title Bar
Send Mail Using Smtp in C++ on Linux
Mpirun: Unrecognized Argument Mca
How to Compile Curlpp on Ubuntu
Segmentation Fault When Sending Struct Having Std::Vector Member
Intercepting/Rerouting Tcp Syn Packets to C++ Program in Linux