     h_B = (int*) malloc (size);
     CUDA_SAFE_CALL (cudaMemcpy (d_A, h_A, size, cudaMemcpyHostToDevice));
 
-    std::cout << "std::cout - start" << std::endl;
-    printf ("stdout - start\n");
+    std::cout << "[std::cout] start" << std::endl;
+    printf ("[printf] start\n");
 
     /// REGULAR PRINT
     // Print to regular stdout
-    std::cout << "Output to stdout:" << std::endl;
+    std::cout << "[std::cout] Output to stdout:" << std::endl;
     printf_redirect<<<1,1>>> (d_A, d_B);
     CUDA_SAFE_CALL (cudaDeviceSynchronize ());
 
     /// REDIRECTION TO STRINGSTREAM
     std::stringstream ss;
-    // Redirect std::cout to a stringstream
-    std::streambuf* backup_cout = std::cout.rdbuf ();
-    std::cout.rdbuf (ss.rdbuf ());
-    // Redirect stdout to a buffer
-    char buf[1024] = "";
-    int backup_stdout = dup (fileno (stdout));
-    freopen ("/dev/null", "w", stdout);
-    setbuf (stdout, buf);
+    // Redirect stdout/std::cout to buffer/stream
+    RedirectPrint rp (ss);
+    rp.redirect (stdout, std::cout);
+    std::cout << "[std::cout] Redirected output:" << std::endl;
 
-    std::cout << "Redirected output:" << std::endl;
     printf_redirect<<<1,N>>> (d_A, d_B);
     CUDA_SAFE_CALL (cudaDeviceSynchronize ());
 
     // Add CUDA buffer to a stringstream
-    ss << buf;
+    rp.flush ();
 
     // Write stringstream to file
     std::ofstream outFile;

// See: http://stackoverflow.com/questions/21238303/redirecting-cuda-printf-to-a-c-stream

#include <cuda.h>
#include <stdio.h>
#include <unistd.h> // dup

#include <iostream>
#include <sstream> // stringstream
#include <fstream> // ofstream

#include "cuda_utils.h"

char* output_file = "printf_redirect.log";

__global__ void printf_redirect(int* src, int* res)
{
    res[threadIdx.x] = threadIdx.x;
    printf("  %i: Hello World!\n", res[threadIdx.x]);
}

int main()

    outFile.close ();

    /// RESET REDIRECTION
    // Redirect back to initial stdout/std::cout
    rp.reset ();

    std::printf ("[printf] After redirection reset\n");
    std::cout << "[std::cout] After redirection reset" << std::endl;

    CUDA_SAFE_CALL (cudaMemcpy(h_B, d_B, size, cudaMemcpyDeviceToHost));

