473,748 Members | 10,048 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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<ostrea m>
#include<sstrea m>
#include<iomani p>
#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
007401F04077555 098C57C01220002 00E0 ";

outClientFile.o pen("Clients.da t", ios::out);
if(!outClientFi le)
{
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.r dbuf();
cout.rdbuf(psbu f);
for(int i=0; i< 10; i++)
{
cout << s1<<endl;
cout.flush();
}
outClientFile.c lose();
return 0;
}
=============== =============== =============== =============== =========
Any Idea pls. discuss..

Thanks

Jul 23 '05 #1
6 4620
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<ostrea m>
#include<sstrea m> you don't need <sstream>, you never use an stringstream #include<iomani p>
#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.goo glegroups.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<ostrea m>
#include<sstrea m>
#include<iomani p>
#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
007401F04077555 098C57C01220002 00E0 ";

outClientFile.o pen("Clients.da t", ios::out);
if(!outClientFi le)
{
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.r dbuf();
cout.rdbuf(psbu f);
for(int i=0; i< 10; i++)
{
cout << s1<<endl;
cout.flush();
}
outClientFile.c lose();
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(st d::ostream &os1, std::ostream &os2)
: m_os1(os1), m_os2(os2) {}
template<typena me T> MultiOstream &operator<<(con st T &v)
{
m_os1 << v;
m_os2 << v;
return *this;
}
MultiOstream &operator<<(std ::ostream &(*f)(std::ostr eam&))
{
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<u nsigned, 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(LogSt ream* 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_ty pe 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 LogLevelManipul ator {

unsigned value;
LogLevelManipul ator(unsigned v) : value(v) { }
};

// This is just a convenience function for creating level manipulators
LogLevelManipul ator log_level(unsig ned n);

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

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

void LogRegister::re gister_stream(s td::ostream& stream, unsigned pri)
{ log_map.insert( std::make_pair( pri, &stream)); }

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

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

LogRegister& LogRegister::in stance()
{ static LogRegister lr; return lr; }

LogRegister::Lo gRegister()
{ }

LogBuffer::LogB uffer(LogStream * s)
: stream_ptr(s)
{ }
LogBuffer::~Log Buffer()
{ flush(); }
LogBuffer::int_ type LogBuffer::over flow(int_type i) {

if(!traits_type ::eq_int_type(i , traits_type::eo f())) {

char_type c = traits_type::to _char_type(i);
buffer.push_bac k(c);
if(c == '\n') flush();
}

return traits_type::no t_eof(i);
}
void LogBuffer::flus h() {

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

LogStream::LogS tream()
: std::ostream(&b uffer), buffer(this)
{ }
unsigned LogStream::get_ level()
{ return iword(level_ind ex); }
const int LogStream::leve l_index = std::ios::xallo c();

// Manipulators

LogLevelManipul ator log_level(unsig ned n)
{ return LogLevelManipul ator(n); }
std::ostream& operator<<(std: :ostream& out, LogLevelManipul ator l) {

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

// Now set the level
out.iword(LogSt ream::level_ind ex) = 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::in stance().regist er_stream(std:: cout, 0);
LogRegister::in stance().regist er_stream(error _stream, 1);
LogRegister::in stance().regist er_stream(log_s tream, 2);

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

// Define some level manipulators
const LogLevelManipul ator
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_er ror("Blah blah");
}
catch(std::exce ption& e) {

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

Jul 23 '05 #4

"radnoraj" <ja******@gmail .com> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.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<ostrea m>
| #include<sstrea m>
| #include<iomani p>
| #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
| 007401F04077555 098C57C01220002 00E0 ";
|
| outClientFile.o pen("Clients.da t", ios::out);
| if(!outClientFi le)
| {
| 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.r dbuf();
| cout.rdbuf(psbu f);
| for(int i=0; i< 10; i++)
| {
| cout << s1<<endl;
| cout.flush();
| }
| outClientFile.c lose();
| 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*********@gm ail.com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.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
6986
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 have tried a few things but no joy what am I missing. Is the another snippet in relation to get_payload to access the body contents print and process to a file. Cheers
0
1445
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 automatically switch its output from the LCD screen to a CRT. Is this possible? Well, the laptop is running Windows XP and the driver doesn't support this function through the Driver's Advanced Settings, however, the same laptop running Win98 allowed...
1
2992
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 OUTSIDE of VisStudio and the text is written into this new window. I remember that I have seen somewhere a VisStudio session where that text was written instead to a little window panel at the bottom of VisStudio (similar to Errors, Warnings,...
1
5018
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 a particular word exists in the line read from the text file.Plz help... Below is my coding: #include <stdio.h> #include <dos.h> #include <stdlib.h> #include <time.h> #include <conio.h> #include <iostream>
0
5009
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 log to be precise), if i specify the name of a custom event log, the listener won't log in it. I've checked in the registry, the log is there. In the event viewer, I
6
17020
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 as "Additional Dependencies" under Linker-Input options. Since those libraries are also in different directory, I specified that library path in project as "Additional Library Directories" under Linker-General options. This is where I see some...
5
18771
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 now forced to do some programming as a small part of my thesis work. Here goes my task and question. I want to read the text file and jus find the displacement old value and replace them with new value and write them in another file.........(In my...
4
2659
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
8366
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 (Not Trace or Debug classes) 2. Set up the trace solution in the application's application.config file 3. Use Visual Basic.NET to test the trace 4. Test the TraceSource using Visual Studio.NET 2005 IDE "Windows application" rather than with...
0
8989
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9367
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9319
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9243
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4599
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4869
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3309
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2780
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2213
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.