Home  >  Article  >  Backend Development  >  How to Capture Standard Output and Error Streams in a String in C ?

How to Capture Standard Output and Error Streams in a String in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-04 01:24:30234browse

How to Capture Standard Output and Error Streams in a String in C  ?

How to Redirect Output to a String in C

For various debugging and testing scenarios, it can be convenient to redirect the standard output and error streams to a string rather than to the console.

Solution: Using std::stringstream

To redirect stdout/stderr to a string, you can utilize the std::stringstream class:

<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>

Guard Class for Buffer Reset

To ensure that the buffer is reset after redirecting, you can create 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>

This guard class guarantees that the buffer is always restored to its original state, even in the event of exceptions.

The above is the detailed content of How to Capture Standard Output and Error Streams in 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