Re-directing 'cout' to a text file

P

Peteroid

I'm doing a managed C++ application. Is there a way to re-direct 'cout' to
output destinations other than the 'black console' that comes up?
Specifically, re-direction to a text file?

Thanks in advance! : )

[==Peteroid==]
 
D

David Lowndes

I'm doing a managed C++ application. Is there a way to re-direct 'cout' to
output destinations other than the 'black console' that comes up?
Specifically, re-direction to a text file?

Doesn't normal command line redirection work?

MyProgram > myfile.txt

Dave
 
P

Peteroid

Hi Dave,

I need to be able to switch the 'cout' output to a text file within the
managed C++ application code. For example, at different execution times I
might want to re-direct this output to different text files. Or maybe to a
printer. And then possibly back to the default 'black console'. That sort of
thing...

[==Peteroid==]
 
N

Nishant S

Try :-

ofstream f;
f.open("d:\\output.txt");
cout.rdbuf(f.rdbuf());

cout << "hello world 1" << endl;
cout << "hello world 2" << endl;

f.close();
 
D

David Lowndes

I need to be able to switch the 'cout' output to a text file within the
managed C++ application code.

Does Nish's suggestion solve the problem?

Dave
 
B

BRG

Peteroid said:
I'm doing a managed C++ application. Is there a way to re-direct 'cout' to
output destinations other than the 'black console' that comes up?
Specifically, re-direction to a text file?

Here is an example of how I do this:
-----------------------------
#include <fstream>
#include <iostream>

int main(void)
{ std::filebuf fb; // declare a file buffer
// connect this file buffer to a file for output
if(fb.open("test.data", std::ios::blush:ut))
{
// test write to cout (console)
std::cout << "*** write to console ***\n";
// set cout's buffer to the filebuf and
// save cout's existing stream buffer to sb
std::streambuf *sb = std::cout.rdbuf(&fb);
// test write to cout (the file)
std::cout << "*** write to file ***\n";
// restore cout's old buffer
std::cout.rdbuf(sb);
// close the file
fb.close();
}
// test write to cout (console)
std::cout << "*** back to console ***\n";
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top