Archived

This topic is now archived and is closed to further replies.

Nash

Redirect std out to file

Recommended Posts

Nash    122
Hello, I''m trying to redirect standard out to a file. Here is the situation. I''m using visual C++. I have an existing app which has many print f statemnts. I want the app to now write out a file of all these print statements. I could call CreateFile and then call WriteFile. However, I would need to replace all my print statements with these WriteFile calls. Is there an easier way? Could I use SetStdHandle? Or maybe connect to pipe created by another app. This other app (the pipe server) would do the actual writing file. Any ideas??

Share this post


Link to post
Share on other sites
Jingo    582
Pretty easy if you use the C++ streams.


#include<fstream>

std::filebuf f;
f.open("myfile.txt", std::ios::out);
std::streambuf* buf = std::cout.rdbuf();
std::cout.rdbuf(&f);
std::cout << "Hello File!" <<std::endl;
std::cout.rdbuf(buf);

Share this post


Link to post
Share on other sites
Jingo    582
If you want to direct std::cout to an edit control, you will need to create your own stream buffer class. In its simplest form you could just derive from the basic_streambuf class and override the virtual overflow(int_type) function to write to the edit control.

[edited by - Jingo on May 26, 2004 2:30:25 PM]

Share this post


Link to post
Share on other sites
LizardCPP    206
why not just do:


#incldue

ofstream fout;
fout.open("myfile.txt");

/* wrtie to file */
fout << "Hello file!" << endl;

fout.close();



dose it really have to be standard out?

LizardCPP

edit: Ok, I read the OP:s post again, nevermind my post...



[edited by - LizardCPP on May 26, 2004 9:20:21 AM]

Share this post


Link to post
Share on other sites
Nash    122
The fopen works fine. I''ve used it before. Thanks. However, I would like the app to write to a pipe. Hence, I connect to the pipe with a CreateFile call. Currently, I would have to replace my printf statements with WriteFile statement to get it to work. Is there a way around this? Or must I start replacing printf statments?

Share this post


Link to post
Share on other sites
botman    122
If it''s just a Win32 console app, what''s wrong with...

myapp.exe > output.txt

...to redirect the printf() output to a file when running the application???

botman

Share this post


Link to post
Share on other sites
Desert Fox    277
iliak,
As Jingo stated, you need to write a stream buffer class that will re-direct the output to your edit control. There really is no simple "make a function call and there you go" way of doing it. I suggest reading up on the streambuf class (MSDN) and buying some advil.

[edited by - desert fox on May 26, 2004 2:25:25 PM]

Share this post


Link to post
Share on other sites