C++Talk.NET Forum Index C++Talk.NET
C++ language newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

using iostream library how do I display output to console a

 
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++)
View previous topic :: View next topic  
Author Message
radnoraj
Guest





PostPosted: Wed Apr 27, 2005 10:03 pm    Post subject: using iostream library how do I display output to console a Reply with quote



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"< 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< cout.flush();
}
outClientFile.close();
return 0;
}
=====================================================================
Any Idea pls. discuss..

Thanks

Back to top
red floyd
Guest





PostPosted: Wed Apr 27, 2005 11:18 pm    Post subject: Re: using iostream library how do I display output to consol Reply with quote



radnoraj wrote:
Quote:
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.

Quote:
=======================================================================
#include <iostream.h
don't use this, use #include #include you don't need #include<iomanip
#include dont use this, use #include You should use


[redacted]

Back to top
David White
Guest





PostPosted: Thu Apr 28, 2005 12:00 am    Post subject: Re: using iostream library how do I display output to consol Reply with quote



"radnoraj" <jadhavac (AT) gmail (DOT) com> wrote

Quote:
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 #include #include #include #include
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"< 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< 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 #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



Back to top
gareth_stockwell@hotmail.
Guest





PostPosted: Thu Apr 28, 2005 7:30 am    Post subject: Re: using iostream library how do I display output to consol Reply with quote


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 #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 #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_stream, 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);
}
}

Back to top
Chris ( Val )
Guest





PostPosted: Thu Apr 28, 2005 10:29 am    Post subject: Re: using iostream library how do I display output to consol Reply with quote


"radnoraj" <jadhavac (AT) gmail (DOT) com> wrote

Quote:
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 #include #include #include #include #include
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"< 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< 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 stringn" );

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



Back to top
Samee Zahur
Guest





PostPosted: Sat Apr 30, 2005 10:05 am    Post subject: Re: using iostream library how do I display output to consol Reply with quote

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':
Quote:
You can take advantage of the fact that an 'ifstream' *is* an
'ostream':

Samee


Back to top
Chris ( Val )
Guest





PostPosted: Sat Apr 30, 2005 3:52 pm    Post subject: Re: using iostream library how do I display output to consol Reply with quote


"Samee Zahur" <samee.zahur (AT) gmail (DOT) com> wrote

Quote:
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 ? :-)

Quote:
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?

Quote:
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.

Quote:
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 Smile
Yes, I did indeed mean to write an 'std::ofstream' object.

Cheers,
Chris Val



Back to top
Display posts from previous:   
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++) All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2006 phpBB Group
SEO toolkit © 2004-2006 webmedic.