Click here to Skip to main content
15,881,413 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how can we redirect output to files using cout?

It depends... Do you want to do it programmatically or from outside the program? If you want to do it outside the program then you can use pipes as you would for any other program.

From inside the program you need to replace the stream buffer cout points at to a file. One option is to open the file you want to redirect to and then swap the stream buffers between cout and the file. However I'm a bit lazy so I'll let you figure out how to do the swap...

More commonly you'll want to re-direct output for the entire program. In this case it's a bit simpler:

std::ofstream output( "c:\\output.txt" );
std::cout.rdbuf( output.rdbuf() );

std::cout << "Urgle!" << std::endl;

Will write "Urgle!\n" to the file c:\output.txt.

On thing to consider is that you shouldn't bother doing this. If you write your code using std::istream and std::ostream then you parameterise where you read from and write to. This makes your code far more usable:

void write_urgle( std::ostream &output )
    output << "Urgle!" << std::endl;

int main()
    std::ofstream output( "c:\\output.txt" );
    write_urgle( output );

will have the same effect and be a bit more reusable in the long run. For example you can unit test write_urgle while you can't unit test (easily) code that uses cout directly.

Er, that's it! Have fun!


Share this answer
try this only change printf to cout <<[^]
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900