Redirecting printed messages to a file

J

Jason Heyes

Here is what I use to redirect printed messages to a file:

std::eek:fstream file("logfile");
std::cout.rdbuf(file.rdbuf());

std::cout << "this message goes to a file" << std::endl;

Will the next message I print go to a file as well?

std::printf("does this message go to a file?");

How do I set things up so that both std::cout and std::printf redirect their
output to the same file? Thanks.
 
P

Pete Becker

Jason said:
Here is what I use to redirect printed messages to a file:

std::eek:fstream 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.
 
J

John Ratliff

Pete said:
Do it this way:

file << "this message goes to a file\n";



Nope.

fprintf(handle, "does this message go to a file? Yes.");



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
 

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

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top