Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   writing to output screen and file simultaneously (http://www.go4expert.com/forums/writing-output-screen-file-t24177/)

heidik 14Dec2010 18:12

writing to output screen and file simultaneously
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:

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
    cout.rdbuf(backup);        // restore cout's original streambuf
    cout << " read existing TRS file" << endl;

xpi0t0s 15Dec2010 14:37

Re: writing to output screen and file simultaneously
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.

FILE *myfile=fopen(...);
char *greeting="Hello world!\n";
fprintf(stdout,greeting); // or just printf(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.

ofstream myfile(...);
string greeting="Hello world";
cout << greeting << endl;
myfile << greeting << endl;

heidik 15Dec2010 15:04

Re: writing to output screen and file simultaneously
Thanks once again xpi0t0s :)

All times are GMT +5.5. The time now is 17:34.