Cout redirection

From NoskeWiki
Jump to: navigation, search

Redirecting Standard Output (Cout) to a Text File

A couple of times I've needed/wanted to output cout operations to a text file. A solution is:

#include <iostream>
#include <fstream>
using namespace std;
 
int main ()
{
  cout << "This is sent to prompt" << endl;
  ofstream fileOutputStream;
  fileOutputStream.open ("test.txt");
  streambuf* sbuf = cout.rdbuf();
  cout.rdbuf(fileOutputStream.rdbuf());
  cout << "This is sent to file" << endl;
  cout.rdbuf(sbuf);
  cout << "This is also sent to prompt" << endl; 
  return 0;
}

However, note that if you call another function from main then fileOutputStream will go out of scope, so if you want to call other functions the file must be made global. i.e.:

#include <iostream>
#include <fstream>
#include <string>
using namespace std; 
 
ofstream fileOutputStream;    // this must be kept somewhere global
 
void redirectStandardOutputToFile (string filePath, bool toPromptAlso)
{
 streambuf* sbuf = cout.rdbuf();
  fileOutputStream.open(filePath.c_str());
  cout.rdbuf(fileOutputStream.rdbuf());
  if (toPromptAlso)
    cout.rdbuf(sbuf);
}
 
void anotherFunction() {
  cout << "The contents of this function is also sent to file";
}
 
int main ()
{
  redirectStandardOutputToFile("test.txt", false);
 
  cout << "This is sent to file" << endl;
  anotherFunction();
  cout << flush;    // is a good policy to flush or else program might close before text is output.
 
  return 0;
}