473,403 Members | 2,366 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,403 software developers and data experts.

using iostream library how do I display output to console as well as write to a file.

Hi,
I am sucessfull in redirecting console output to a file. but in this
case nothing is displayed on the console, cout output is written to
file without display.
how do write the output to console as well as to file, my code is as
below,
================================================== =====================
#include <iostream.h>
#include<ostream>
#include<sstream>
#include<iomanip>
#include <fstream.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
ofstream outClientFile;
streambuf *psbuf;
char * s1 = " 00010 00000036 1 440 430 F 11
007401F04077555098C57C0122000200E0 ";

outClientFile.open("Clients.dat", ios::out);
if(!outClientFile)
{
cerr << "File could not be Opened"<<endl;
exit(1);
}
cout << "You will not see any screen Output" << endl
<< "Console Output is redirected to a File"<< endl << "... \n";
psbuf = outClientFile.rdbuf();
cout.rdbuf(psbuf);
for(int i=0; i< 10; i++)
{
cout << s1<<endl;
cout.flush();
}
outClientFile.close();
return 0;
}
================================================== ===================
Any Idea pls. discuss..

Thanks

Jul 23 '05 #1
6 4587
radnoraj wrote:
Hi,
I am sucessfull in redirecting console output to a file. but in this
case nothing is displayed on the console, cout output is written to
file without display.
how do write the output to console as well as to file, my code is as
below,
You need to write a custom streambuf that will write to two places at once.
================================================== =====================
#include <iostream.h> don't use this, use <iostream> #include<ostream>
#include<sstream> you don't need <sstream>, you never use an stringstream #include<iomanip>
#include <fstream.h> dont use this, use <fstream> #include <stdlib.h>

You should use <cstdlib> instead, but this is not an error.

[redacted]
Jul 23 '05 #2
"radnoraj" <ja******@gmail.com> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...
Hi,
I am sucessfull in redirecting console output to a file. but in this
case nothing is displayed on the console, cout output is written to
file without display.
how do write the output to console as well as to file, my code is as
below,
================================================== =====================
#include <iostream.h>
#include<ostream>
#include<sstream>
#include<iomanip>
#include <fstream.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
ofstream outClientFile;
streambuf *psbuf;
char * s1 = " 00010 00000036 1 440 430 F 11
007401F04077555098C57C0122000200E0 ";

outClientFile.open("Clients.dat", ios::out);
if(!outClientFile)
{
cerr << "File could not be Opened"<<endl;
exit(1);
}
cout << "You will not see any screen Output" << endl
<< "Console Output is redirected to a File"<< endl << "... \n";
psbuf = outClientFile.rdbuf();
cout.rdbuf(psbuf);
for(int i=0; i< 10; i++)
{
cout << s1<<endl;
cout.flush();
}
outClientFile.close();
return 0;
}
================================================== ===================
Any Idea pls. discuss..


I needed to do this myself recently and used my own multi-ostream. It only
supports << operations, but that's all I needed. Example program:

#include <ostream>
#include <iostream>
#include <fstream>
#include <iomanip>

class MultiOstream
{
public:
MultiOstream(std::ostream &os1, std::ostream &os2)
: m_os1(os1), m_os2(os2) {}
template<typename T> MultiOstream &operator<<(const T &v)
{
m_os1 << v;
m_os2 << v;
return *this;
}
MultiOstream &operator<<(std::ostream &(*f)(std::ostream&))
{
m_os1 << f;
m_os2 << f;
return *this;
}

private:
std::ostream &m_os1;
std::ostream &m_os2;
};

int main()
{
std::ofstream ofs("File.out");
MultiOstream mos(std::cout, ofs);
mos << std::setw(20) << "Hello world" << std::endl;
}

The second << function had to be a template specialization with VC++ 6.0,
but VC++ 7.0 didn't like that and only accepted a non-template function. I
don't know if there's a way to avoid that special case altogether.

DW
Jul 23 '05 #3

Radnoraj,

I also needed this kind of functionality, so I wrote a framework which
allows you to register any number of streams, then use a `dispatcher'
stream which wil write any output to all of the streams which you
registered.

The basic idea is as follows:
1. Have a singleton registry object (LogRegistry), which holds pointers
to the output streams
2. Implement the dispatching mechanism by writing a LogBuffer class,
derived from std::streambuf. The flush() function in this buffer gets
all the registered streams from the LogRegistry object, and writes to
each one in turn. (See Josuttis if you're not up on the internals of
iostreams)
3. The class which you actually use on the lhs of your << operators,
LogStream, is simply a std::ostream whose internal buffer is an
instance of LogBuffer.

I added one extra feature which is that each registered stream is
associated with a `logging level'. This is just a number which allows
you to choose which stream(s) each message is sent to. In this way you
can have a main log file to which all messages get sent, an error file
which only receives warning messages, and an error file to which any
serious errors are written. The user selects the appropriate level for
any given message using stream manipulators.

The following code, which should compile standalone, illustrates the
idea - you should be able to hack this to suit your needs.

HTH
Gareth


//----------------
// Interface
//-------------

#include <streambuf>
#include <ostream>
#include <iomanip>
#include <map>
// A class with which users can register logging streams
struct LogRegister {

typedef std::multimap<unsigned, std::ostream*> log_map_t;
log_map_t log_map;

void register_stream(std::ostream& stream, unsigned pri);

void write(const std::string& s, unsigned level) const;

static LogRegister& instance();

private:
LogRegister();
};
// Forward declaration
class LogStream;

// Custom streambuf
struct LogBuffer : public std::streambuf {

LogBuffer(LogStream* s);
~LogBuffer();

private:

// The buffer holds a pointer to the stream, as it needs to query

// the stream to obtain the current logging level
LogStream* stream_ptr;
std::string buffer;

int_type overflow(int_type i);
void flush();
};
// The actual stream class (the `message dispatcher')
class LogStream : public std::ostream {

LogBuffer buffer;

public:

// Index into the ios state array
static const int level_index;

LogStream();
unsigned get_level();
};
// Manipulators allowing the user to specify logging levels
struct LogLevelManipulator {

unsigned value;
LogLevelManipulator(unsigned v) : value(v) { }
};

// This is just a convenience function for creating level manipulators
LogLevelManipulator log_level(unsigned n);

// The function which modifies the stream's logging level according to
// a manipulator object
std::ostream& operator<<(std::ostream& out, LogLevelManipulator l);

//--------------------
// Implementation
//------------------

void LogRegister::register_stream(std::ostream& stream, unsigned pri)
{ log_map.insert(std::make_pair(pri, &stream)); }

void LogRegister::write(const std::string& s, unsigned level) const {

for(log_map_t::const_iterator i = log_map.lower_bound(level);
i != log_map.end(); ++i)
*(i->second) << s;
}

LogRegister& LogRegister::instance()
{ static LogRegister lr; return lr; }

LogRegister::LogRegister()
{ }

LogBuffer::LogBuffer(LogStream* s)
: stream_ptr(s)
{ }
LogBuffer::~LogBuffer()
{ flush(); }
LogBuffer::int_type LogBuffer::overflow(int_type i) {

if(!traits_type::eq_int_type(i, traits_type::eof())) {

char_type c = traits_type::to_char_type(i);
buffer.push_back(c);
if(c == '\n') flush();
}

return traits_type::not_eof(i);
}
void LogBuffer::flush() {

LogRegister::instance().write(buffer, stream_ptr->get_level());
buffer.clear();
}
// Stream class

LogStream::LogStream()
: std::ostream(&buffer), buffer(this)
{ }
unsigned LogStream::get_level()
{ return iword(level_index); }
const int LogStream::level_index = std::ios::xalloc();

// Manipulators

LogLevelManipulator log_level(unsigned n)
{ return LogLevelManipulator(n); }
std::ostream& operator<<(std::ostream& out, LogLevelManipulator l) {

// First flush the stream
out << std::flush;

// Now set the level
out.iword(LogStream::level_index) = l.value;
return out;
}
//----------------------
// Example
//--------------

#include <fstream>
#include <iostream>
#include <stdexcept>

int main() {

std::ofstream log_stream("/tmp/test.log");
std::ofstream error_stream("/tmp/test.err");

// Register the streams. The higher the level, the more messages
// that stream will receive. Here std::cout is reserved for only
// the serious messages which the user needs to see right now.
LogRegister::instance().register_stream(std::cout, 0);
LogRegister::instance().register_stream(error_stre am, 1);
LogRegister::instance().register_stream(log_stream , 2);

// This is the `dispatcher' object
LogStream multi;

// Define some level manipulators
const LogLevelManipulator
normal = log_level(2),
error = log_level(1),
fatal = log_level(0);

try {

// Set the initial logging level
multi << normal;

// Most program output just goes to the log; not printed to the
// console
multi << "Standard message; just sent to the 'log' stream"
<< std::endl;
multi << "Another routine message" << std::endl;

// Oops, an error occurred - this is logged to error_stream
// but does not abort the program
multi << error << "A nasty error occurred..." << std::endl
<< normal;
// Note that the log level has been reset to `normal'

// ... and back to routine logging
multi << "Back to normal" << std::endl;

// Now something nasty happens, resulting in an uncaught
// exception propagating to the top level. This will abort the
// program.
throw std::runtime_error("Blah blah");
}
catch(std::exception& e) {

multi << fatal << "A catastrophic error occurred:" << std::endl
<< e.what() << std::endl
<< "Aborting..." << std::endl;
log_stream.close();
error_stream.close();
exit(1);
}
}

Jul 23 '05 #4

"radnoraj" <ja******@gmail.com> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...
| Hi,
| I am sucessfull in redirecting console output to a file. but in this
| case nothing is displayed on the console, cout output is written to
| file without display.
| how do write the output to console as well as to file, my code is as
| below,
| ================================================== =====================
| #include <iostream.h>
| #include<ostream>
| #include<sstream>
| #include<iomanip>
| #include <fstream.h>
| #include <stdlib.h>
|
| int main(int argc, char* argv[])
| {
| ofstream outClientFile;
| streambuf *psbuf;
| char * s1 = " 00010 00000036 1 440 430 F 11
| 007401F04077555098C57C0122000200E0 ";
|
| outClientFile.open("Clients.dat", ios::out);
| if(!outClientFile)
| {
| cerr << "File could not be Opened"<<endl;
| exit(1);
| }
| cout << "You will not see any screen Output" << endl
| << "Console Output is redirected to a File"<< endl << "... \n";
| psbuf = outClientFile.rdbuf();
| cout.rdbuf(psbuf);
| for(int i=0; i< 10; i++)
| {
| cout << s1<<endl;
| cout.flush();
| }
| outClientFile.close();
| return 0;
| }
| ================================================== ===================
| Any Idea pls. discuss..

You can take advantage of the fact that an 'ifstream' *is* an
'ostream':

inline void Print( std::ostream& Stream, const char* Source )
{
Stream << Source;
}

inline void LogToStreams( std::ostream& ToFile,
std::ostream& ToScreen, const char* Source )
{
Print( ToFile, Source );
Print( ToScreen, Source );
}

int main()
{
std::ofstream ofs( "System.Log.txt" );
LogToStreams( ofs, std::cout, "Some source string\n" );

return 0;
}

This just uses a helper function called 'Print', but it's
pretty straight forward.

*NOTE* There is no error checking provided to keep the
example clear and to the point.

Btw, what's wrong with utilising the 'std::cerr' object
in conjunction with the 'std::cout' object ?

You could just redirect one of them, and use the other
as per normal ?

Cheers,
Chris Val
Jul 23 '05 #5
Well, I'm not sure about this, but I don't think cerr and cout even
needs to be the same physical device by default. Using cerr leaves the
*user* with no neat way of suppressing the output (even though the
programmer might want it displayed). Plus, it hinders piping and other
neat things we do with cout - the point is cerr is just not meant to be
used for normal outputs, it is there for error messages only (which is
less likely to need supressions).

And I think there's been a typo here - I'm sure you mean 'ofstream':
You can take advantage of the fact that an 'ifstream' *is* an
'ostream':


Samee

Jul 23 '05 #6

"Samee Zahur" <sa*********@gmail.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com...
| Well, I'm not sure about this, but I don't think cerr and cout even
| needs to be the same physical device by default.

Well, I'm not sure what you're not sure about ? :-)

| Using cerr leaves the *user* with no neat way of suppressing the
| output (even though the programmer might want it displayed).

I don't follow you, I'm sorry.
The first line seems to contradict the last?

| Plus, it hinders piping and other neat things we do with cout -
| the point is cerr is just not meant to be used for normal outputs,
| it is there for error messages only (which is less likely to need
| supressions).

I'm still not sure what you're getting at, but just let me clarify,
that what I was alluding to was to redirect the std::cerr object to
write to file, and use the std::cout object to continue writing to
the console.

| And I think there's been a typo here - I'm sure you mean 'ofstream':
| > You can take advantage of the fact that an 'ifstream' *is* an
| > 'ostream':

Ah - Good catch :-)
Yes, I did indeed mean to write an 'std::ofstream' object.

Cheers,
Chris Val
Jul 23 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
by: Chuck Amadi | last post by:
Sorry to bovver you again (again) here's script. I still can't see why the get_payload() doesn't produce the plain text message body of an emails in the testwwws users mailbox. As you can see I...
0
by: Drydo | last post by:
In short, is it possible to swap/change the display output of a laptop to a CRT programmatically? The scenario is that we have a laptop that at the startup of a specific application would...
1
by: Steven Prasil | last post by:
When I run/debug a program with Console.out.write statements inside and the program execution reaches this statement then a new console/command prompt window (this with black background) is opened...
1
by: Rajeev_nair_1981 | last post by:
I have written a program which executes an application (netview) and logs the output into a text file.Later I open and read this file line by line using getline() function.Now I need to check whether...
0
by: Eniac | last post by:
Hello, I've started using Enterprise Library 2.0 recently and I've encountered a problem that seems to be ... well... undocumented :) Basically, when I set a Trace Listener (formatted event...
6
by: =?Utf-8?B?WW9naSBXYXRjaGVy?= | last post by:
Hello, I am using Visual Studio-2003. I created a project to build my library. Since I am using third party libraries as well, I have specified those additional library dependencies in project...
5
by: sheriff | last post by:
Dear friends, im a newbee for this forum and c++ im doing my MSc in Simulation Tech in mech. Engineering. My knowledge of c++ is very little which I had during my UG studies Long long ago .I am...
4
by: Herman.Schultz | last post by:
Hi, How can I use iostream library in c++ to copy a file from i th byte to an output file? Thank you.
1
by: mquincey | last post by:
One of the features offered by .NET 2.0 is the use of the TraceSource class. In an attempt to demonstrate its use, I wanted to run my test under the following conditions: 1. Use TraceSource class...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.