-1

In my program I am switching my cout to write to a file using the following:

int newstdout = open("myFile.txt",O_WRONLY|O_CREAT,S_IRWXU|S_IRWXG|S_IRWXO);    
close(1);    
dup(newstdout);    
close(newstdout);

How would I later in the program switch back to my cout printing to the screen(terminal)?

Woodford
  • 3,746
  • 1
  • 15
  • 29
code
  • 1

1 Answers1

3

The correct way to make cout (or any other stream) output to a different target is to call its rdbuf() method to swap in a different stream buffer. You can then swap back in the old buffer later, if needed. For example:

#include <iostream>
#include <fstream>

std::ofstream outfile("myFile.txt");
auto cout_buff = std::cout.rdbuf();

std::cout.rdbuf(outfile.rdbuf());
// anything written to std::cout will now go to myFile.txt instead...

std::cout.rdbuf(cout_buff);
// anything written to std::cout will now go to STDOUT again...
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770