Pete Becker wrote:
Jason Heyes wrote:
Here is what I use to redirect printed messages to a file:
std::ofstream file("logfile");
std::cout.rdbuf(file.rdbuf());
std::cout << "this message goes to a file" << std::endl;
Do it this way:
file << "this message goes to a file\n";
Will the next message I print go to a file as well?
std::printf("does this message go to a file?");
Nope.
fprintf(handle, "does this message go to a file? Yes.");
How do I set things up so that both std::cout and std::printf redirect
their output to the same file? Thanks.
If you want to write to a file, write to a file. If you want to write to
the console, write to cout or stdout. They write to the console, and
it's up to the user to redirect them.
I agree with him, but if you really want to redirect the standard
streams, you can use std::freopen, e.g.
#include <cstdio>
#include <iostream>
std::freopen("stdout.txt", "w", stdout);
std::freopen("stderr.txt", "w", stderr);
std::cout << "this will be written to stdout.txt\n";
std::printf("so will this...\n");
std::cerr << "this will be written to stderr.txt\n";
std::fprintf(stderr, "so will this...\n");
I'd stay away from this unless you REALLY want ALL stdout and stderr
output redirected to a file. Much better to use ofstream with a log
file. The original streams get closed when you use freopen.
--John Ratliff