Roronoa Zoro
Roronoa Zoro

Reputation: 1013

Redirect some output to command prompt, and some to file?

I'm trying to redirect some of the standard output to a text file, and some other to the command prompt.

I'm currently outputting all of it to a file, but I'd like to output some to the command prompt, so I can know at least (get some hits), on what's been recorded (since it takes like 10 minutes to run this code)

This is what I'm doing;

FILE *stream ;

std::stringstream ss;
ss << "K_file.txt";

if((stream = freopen(ss.str().c_str(), "w", stdout)) == NULL)
    exit(-1);

std::cout<<"blah blah blah...";

Edit based on comment;

'some' is part of the code where I would like to explicitly specify, example;

for(int i = 0; i<1000; i++)
{
    std::cout<<"I would like this to go to the file - since it's detailed";
}    
std::cout<<"loop finished - I would like this to go to the command prompt";

This might not be the best example but I hope you get the point.

Upvotes: 0

Views: 1203

Answers (2)

Branko Dimitrijevic
Branko Dimitrijevic

Reputation: 52107

You could "abuse" standard output and standard error stream for that. For example:

#include <iostream>

void main() {
    std::cout << "standard output";
    std::cerr << "standard error";
}

Now, if you redirect just the standard error to file...

your_program.exe 2> file.txt

...you'll get "standard output" in console window and "standard error" in file.txt.

(NOTE: This is Windows redirection syntax - I'm sure you'll have no trouble doing redirection on other OSes if you need to.)

Upvotes: 3

jweyrich
jweyrich

Reputation: 32240

I think this might help:

#include <fstream>
#include <iostream>

class stream_redirector {
public:
    stream_redirector(std::ostream& dst, std::ostream& src)
        : src(src), sbuf(src.rdbuf())
    {
        src.rdbuf(dst.rdbuf());
    }
    ~stream_redirector() {
        src.rdbuf(sbuf);
    }
private:
    std::ostream& src;
    std::streambuf* const sbuf;
};

int main() {
    std::ofstream log("log.txt");
    std::cout << "Written to console." << std::endl;
    {
        // We redirect std::cout to log.
        stream_redirector redirect(log, std::cout);
        std::cout << "Written to log file" << std::endl;
        // When this scope ends, the destructor will undo the redirection.
    }
    std::cout << "Also written to console." << std::endl;
}

Upvotes: 2

Related Questions