writing to output screen and file simultaneously

Discussion in 'C++' started by heidik, Dec 14, 2010.

  1. heidik

    heidik New Member

    Joined:
    Oct 23, 2010
    Messages:
    69
    Likes Received:
    0
    Trophy Points:
    0
    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;
    }
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    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;
    
     
  3. heidik

    heidik New Member

    Joined:
    Oct 23, 2010
    Messages:
    69
    Likes Received:
    0
    Trophy Points:
    0
    Thanks once again xpi0t0s :)
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice