0

Is it possible to show cout output on a file instead of showing it in the console/terminal?

#include <iostream>
#include <fstream>

void showhello()
{
    cout << "Hello World" << endl;
}

int main(int argc, const char** argv)
{
    ofstream fw;
    fw.open("text.txt");
    fw << showhello() << endl;
}

If I simply put the cout << "Hello World" << endl; in the main, it will of course show "Hello World" in the terminal. Now instead of showing it in the terminal, I want to make it show in the text.txt file.

Restriction: Let's say the function showhello() contains a thousand of cout output, so you cannot use something like:

fw << "Hello World" << endl;

or a copy paste in a string. It must be fw << function.

Lord Rixuel
  • 1,173
  • 6
  • 24
  • 43
  • What you are doing should work fine as far as I can understand what you want. – Galik Oct 05 '14 at 04:48
  • [`How to redirect cin & cout to a file`](http://stackoverflow.com/questions/10150468/how-to-redirect-cin-and-cout-to-files) – DOOM Oct 05 '14 at 04:50
  • 1
    Chances are you'll be better off refactoring `showHello` to take an `ostream` as an argument and output to that. You'll have the option of providing an overload of `showHello` that takes no arguments calls the refactored version passing in `std::cout`. – Captain Obvlious Oct 05 '14 at 05:55
  • possible duplicate of [Is it possible to pass cout or fout to a function?](http://stackoverflow.com/questions/10356300/is-it-possible-to-pass-cout-or-fout-to-a-function) – GingerPlusPlus Oct 05 '14 at 11:35

2 Answers2

3

You can do re-direction like following :

std::streambuf *oldbuf = std::cout.rdbuf(); //save 
std::cout.rdbuf(fw.rdbuf()); 

showhello(); // Contents to cout will be written to text.txt

//reset back to standard input
std::cout.rdbuf(oldbuf);
P0W
  • 46,614
  • 9
  • 72
  • 119
  • It really works. I'm a little surprised to see you simply need to put the function between the streambuf and cout.rdbuf. – Lord Rixuel Oct 05 '14 at 05:50
3

You can take a reference to stream as argument:

std::ostream& showhello(std::ostream& stream) {
    return stream << "Hello World";
}

//Usage (I was surpised that it works, thanks @T.C.):

ofstream fw;
fw.open("text.txt");
std::cout << showhello << '\n';

//Alternatively:

showhello(fw) << '\n';

I'm using '\n' instead of std::endl, because std::endl forces flushing the stream.
When you write to console, the difference may be almost unnoticeable, but when you write to disk,
it forces to get access to disk right now, instead of waiting until there is enoungh data to make saving to disk efficent.

GingerPlusPlus
  • 5,336
  • 1
  • 29
  • 52
  • 1
    The cool thing about this is that if you do this you can actually write `fw << showhello << '\n'`. – T.C. Oct 05 '14 at 10:26