lundi 13 juin 2016

Swapping a stringstream for cout


With glibc's stdio, I can swap a memstream for stdout, thereby capturing the output of a piece of code compiled to output to stdout:

#include <stdio.h>

void swapfiles(FILE* f0, FILE* f1){ FILE tmp; tmp = *f0; *f0 = *f1; *f1 = tmp; }

void hw_c(){ puts("hello c world"); }

int c_capt(){
  FILE* my_memstream;
  char* buf  = NULL;
  size_t bufsiz = 0;

  if( (my_memstream = open_memstream(&buf, &bufsiz)) == NULL) return 1;

  FILE * oldstdout = stdout;

  swapfiles(stdout, my_memstream);
  hw_c();
  swapfiles(stdout, my_memstream);

  fclose(my_memstream);
  printf("Captured: %sn", buf);
}

I'm curious if the same is possible for iostreams. My naive attempt won't compile:

#include <iostream>
#include <string>
#include <sstream>

void hw_cc(){ std::cout<<"hello c++ worldn"; }
int cc_capt(){
  using namespace std;

  stringstream ss;
  string capt;

  //std::swap(ss,cout); //<- the compiler doesn't like this
  hw_cc();
  //std::swap(ss,cout); 

  cout<<"Captured: "<<capt<<'n';
}

int main(int argc, char** argv){
  c_capt();
  puts("---------------------------------");
  cc_capt();
  return 0;
}

Aucun commentaire:

Enregistrer un commentaire