Home > Backend Development > C++ > Can You Redirect Standard Output (stdout) and Standard Error (stderr) to a String in C ?

Can You Redirect Standard Output (stdout) and Standard Error (stderr) to a String in C ?

Barbara Streisand
Release: 2024-11-02 22:14:30
Original
555 people have browsed it

Can You Redirect Standard Output (stdout) and Standard Error (stderr) to a String in C  ?

Redirecting stdout/stderr to a String

Many discussions have centered around redirecting stdout/stderr to a file. However, is it possible to redirect this output to a string?

Solution

Yes, redirection to an std::stringstream object is feasible:

<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>
Copy after login

To ensure automatic reset of the buffer, consider using a guard class:

<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>
Copy after login

The above is the detailed content of Can You Redirect Standard Output (stdout) and Standard Error (stderr) to a String in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template