writing to output screen and file simultaneously

heidik's Avatar, Join Date: Oct 2010
Contributor
Hello everyone!

is there anyway I can write the output of a program both to the file and the output screen simultaneously? Code for writing to a file is as follows:
Code:
string fpath = "/usr/local/" + std::string("/Fouput_") + std::string(".log"); 

streambuf *psbuf, *backup;
fstream filestr1;
    
ifstream file(fpath.c_str());
if (!file)
{
    cout << " file does not exist - create one" << endl;

    filestr1.open (fpath.c_str());
                
    backup = cout.rdbuf();     // back up cout's streambuf
    psbuf = filestr1.rdbuf();   // get file's streambuf
    cout.rdbuf(psbuf);         // assign streambuf to cout
             
    Totals();
             
    cout.rdbuf(backup);        // restore cout's original streambuf
    filestr1.close();
}         
else
{
    cout << " read existing TRS file" << endl;
}
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
At the command line, you can use tee, which takes a filename as an argument and writes whatever is piped into it to that file and to the screen, e.g.

ls | tee mydir

If you want to do it under program control instead, then just write to stdout, which is a file descriptor that is preopened for you, and to a file handle that you open yourself, e.g.
Code:
FILE *myfile=fopen(...);
char *greeting="Hello world!\n";
fprintf(stdout,greeting); // or just printf(greeting);
fprintf(myfile,greeting);
In C++ stream parlance you could use ofstream which is like ifstream but for output instead of input. And you already know how to use cout.
Code:
ofstream myfile(...);
string greeting="Hello world";
cout << greeting << endl;
myfile << greeting << endl;
heidik's Avatar, Join Date: Oct 2010
Contributor
Thanks once again xpi0t0s