Home >Backend Development >C++ >Can you redirect stdout and stderr to a string in C ?

Can you redirect stdout and stderr to a string in C ?

Susan Sarandon
Susan SarandonOriginal
2024-11-02 22:27:30602browse

Can you redirect stdout and stderr to a string in C  ?

Redirecting stdout/stderr to a String

Redirecting stdout and stderr to files is a common task, but can output to a string be achieved?

Answer:

Yes, it's possible to redirect stdout and stderr to an std::stringstream:

<code class="cpp">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"</code>

To ensure the buffer is always reset, a guard class can be used:

<code class="cpp">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;
};</code>

The above is the detailed content of Can you redirect stdout and stderr to a string in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn