Sending cout to a log file.

Hi,

I have been trying to figure out how to write all of my cout to a txt file, so that I can look at it later outside of the terminal.

I can easily do this with an ofstream but I don't know how to "redirect" cout so that it also writes it to a log file.

I need something like

1
2
3
4
5
6
7
void myprogram(){

  // Some line here to make this work

  cout << "Hi \n";

}


to yield an output file containing the word hi.
You are going to have to use an ofstream as far as I know. Not that much work. To make it easier on yourself just make a function that takes a std::string as a parameter and prints it to the file. You can then just call the function instead of writing an output statement.
Wrapping the ostream object will prevent you from using some of its properties. The insertion operator (<<) should really be used directly to write the string to the stream.

But you could modify the function myprogram() to take an ostream.

1
2
3
4
5
void myprogram(ostream& os){

  os << "Hi" << endl; // use endl to end lines, rather than just "\n"

}


Then you can call the function with cout or a file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <fstream>

void myprogram(ostream& os); // forward definition

int main()
{
    // write to cout
    myprogram(cout);

    // and now to the file example.txt
    ofstream ofs("example.txt");
    if(ofs.is_open())
    {
        myprogram(ofs);
    }

    return 0;
}

// myprogram function goes here 

Last edited on
@andywestken: That worked perfectly. I didn't think to pass the ostream by reference. Thanks a lot.
Topic archived. No new replies allowed.