473,789 Members | 2,544 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

defining a custom output facility

I'd like to create a "custom output facility". In other words, I want
an object whose use is similar to std::cout/std::cerr, but offers more
flexibility. Instead of simply writing the parameter to stdout/stderr,
I'd like it to write to stdout, to a file, and/or call a logging
function.

So my output function might look something like this:

OutputFacility& OutputFacility: :put(const std::string& s) {
cout << s; // print to stdout
write_to_logfil e(s); // also calling logging function
return *this;
}

Now I can define the << operator to be an alias for put().

My question is: do I have to define put() for every type of input I
expect to print? I.e., I'd like this to work with all primitive types,
int, char, double, float, etc.

Right now I'm thinking that the OutputFacility class could have a
std::ostringstr eam as a private member; every version of
OutputFacility: :put() would just in turn call the ostringstream put()
method, THEN call the actual output functions (e.g. write_to_logfil e()).

It seems like there should be a simpler method of defining my put
method, i.e. instead of overloading it and defining it multiple times,
if I could just define it once with a "magical" parameter that means
"take anything that can be converted to a string".

Thanks for any advice!
Matt

--
Matt Garman
email at: http://raw-sewage.net/index.php?file=email
Jul 22 '05
12 3216
On Fri, 16 Jan 2004 13:02:45 +0100, Karl Heinz Buchegger
<kb******@gasca d.at> wrote:
You want to change a string in the behaviour of the transportation
layer, thus your approach should be to write a customized stream
buffer and make the stream use that instead of the one it was born
with.
Okay, I think I'm starting to get it :) Thank you!

Since I want my custom output facility to write to stdout AND a log (or
window or whatever), does that mean that my custom streambuf's
implementation will write to stdout? It seems like I would be
duplicating what the standard library already does. (In other words, is
there a way to say "do what you already do, AND do these other things"?)

Let me re-iterate just to make sure my understanding is correct:

- stream object (e.g. cout) formats data
- stream object passes formatted data to stream buffer
- stream buffer object delivers data to its destination (e.g.
stdout, logfile, window, etc)
there would be some sort of hook in printf, which allows you to get a
grasp at the string printf produces internally before printf sends
this string to the device. In this way you don't need to change any
printf calls but just hook into it, and do whatever you want with the
printf generated string.


That's exactly what sprintf() (and snprintf() on some systems)
does---formats a string and puts it in a buffer. But that opens you up
to all kinds of potential buffer overrun problems. It's a lot of work
to make sure this is done safely. (That's why I'm using c++!)

Thanks again for your help and patience,
Matt

--
Matt Garman
email at: http://raw-sewage.net/index.php?file=email
Jul 22 '05 #11
Matt Garman wrote:

Since I want my custom output facility to write to stdout AND a log (or
window or whatever), does that mean that my custom streambuf's
implementation will write to stdout?
typically yes.
But wait: when you tell the stream object to use a different stream
buffer, you get a hold on the stream buffer actually used by the
stream. So you simply could forward all output to the original stream
buffer AND process it on your own.

Let me re-iterate just to make sure my understanding is correct:

- stream object (e.g. cout) formats data
- stream object passes formatted data to stream buffer
- stream buffer object delivers data to its destination (e.g.
stdout, logfile, window, etc)
yep.
there would be some sort of hook in printf, which allows you to get a
grasp at the string printf produces internally before printf sends
this string to the device. In this way you don't need to change any
printf calls but just hook into it, and do whatever you want with the
printf generated string.


That's exactly what sprintf() (and snprintf() on some systems)
does---formats a string and puts it in a buffer. But that opens you up
to all kinds of potential buffer overrun problems. It's a lot of work
to make sure this is done safely. (That's why I'm using c++!)


OK.
So with that analogy an output operation in a stream does something
like that:

void DoOutput( ..... )
char buffer[whatever];
sprintf( buffer, ..... );
puts( buffer );
}

Throughout your program you always use DoOutput() instead of printf().
If you need to retarget the output, you add the retargeting by
replacing the puts() with something else.
In the above, the puts() would be the equivalent to the stream buffer
object (and of course the whole thing wrapped in a class with some
nicer syntax for using and getting rid of the buffer overflow problem,
etc. But that's not the point right now). For retargeting the output
you replace the stream buffer with something else. And in the same
sense as in the DoOutput() solution the caller of this function doesn't
notice anything of the retargeting, the user of a stream object doesn't
notice anything when the stream buffer is replaced. For him everything
stays the same, even custom operator<< or operator>> work as they ever did.
Only the output is retargeted to somwehere else.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #12
Okay, thank you for all the verbose feedback! I think I finally
understand the concepts.

So what if I were to take it a step further, and say that my custom
output facility should be able to write to any number of media? In
other words, combine a streambuf with a vector?

I did just that in the code below (tested with g++ under Linux). Is
what I did the "best" way to solve that problem?

Note that I'd actually write a convenience wrapper class for ostream as
well, just to easily facilitate adding and removing streambufs.

Thanks again for all the help!
Matt

#include <iostream>
#include <fstream>
#include <streambuf>
#include <vector>

class streambufvec : public std::streambuf {
public:
typedef std::char_trait s<char> traits_type;
typedef traits_type::in t_type int_type;
typedef std::vector< std::streambuf* > streambufvec_t;

streambufvec()
{ streambufs.push _back(std::cout .rdbuf()); }

streambufvec(st reambufvec_t sbvec)
{ streambufs.inse rt(streambufs.e nd(),
sbvec.begin(), sbvec.end()); }

streambufvec(st d::streambuf* sb)
{ streambufs.push _back(sb); }

virtual ~streambufvec()
{ streambufs.clea r(); }

void push_back(std:: streambuf* sb)
{ streambufs.push _back(sb); }

protected:
inline int_type overflow(int_ty pe c)
{
streambufvec_t: :iterator ii;
for (ii=streambufs. begin(); ii!=streambufs. end(); ++ii) {
if (traits_type::e of() == (*ii)->sputc(c)) {
return traits_type::eo f();
}
}
return c;
}

private:
streambufvec_t streambufs;
};
int main(int argc, char** argv)
{
std::ofstream file1("file1.tx t");
std::ofstream file2("file2.tx t");
std::ofstream file3("file3.tx t");

streambufvec sbvec;
sbvec.push_back (file1.rdbuf()) ;
sbvec.push_back (file2.rdbuf()) ;
sbvec.push_back (file3.rdbuf()) ;

sbvec.push_back (std::cerr.rdbu f());

std::ostream of(&sbvec);

of << "Hello, world!" << std::endl;

return 0;
}

--
Matt Garman
email at: http://raw-sewage.net/index.php?file=email
Jul 22 '05 #13

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

Similar topics

0
1408
by: Brian van den Broek | last post by:
Hi all, IDLE refuses to launch, and I believe it is because I attempted to define a custom key-binding that it doesn't like. I was recently defining a custom keybinding in IDLE 1.1 under Python 2.4 on WinMe. (I was using the simpler of the two binding definition interfaces.) When done, I hit the buttons for 'OK' (or however it is labelled -- I cannot currently check), but the definition dialog remained open. After several tries, I hit...
3
2401
by: Paul Bowman | last post by:
Hi All Java has a facility where you can send output to a DOS window using System.out.println. This is useful while developing as you can see what it going in your code. Does .Net provide a similar facility? I notice that when a Windows app runs there is an output window that contains messages from the compiler etc. Is it possible to 'plug' into this?
0
988
by: Samir Patel | last post by:
Hi Everybody hai i am fine what about all of u? i have a problem regarding to ASP.NET custom control , can anybody help me? my problem is when i placed my custom control on page at design time i am not able to select the child control of my custom control,how can i do this second thing how to allow custom template control's template editing facility in design mode
19
2989
by: Dales | last post by:
I have a custom control that builds what we refer to as "Formlets" around some content in a page. These are basically content "wrapper" sections that are tables that have a colored header and provide an open TD with a DIV in it for the content of this formlet. (The DIV is for DHTML to hide and show the content) I've created a web page showing step by step the two problems I'm encountering. This problem is much easier to see than it...
5
1790
by: Sadeq | last post by:
Is it possible to define custom attributes for arrays? And if so, how can I retrieve them? I mean I want to define sth like: int MyArray; and then retrieve the value of the custom attribute on demand. I used the GetCustomAttributes method on MyArray, but the results "length" was
17
7649
by: rdemyan | last post by:
My app creates a building report. My users have requested that I provide functionality to e-mail these "building reports" to building managers once a month. So assuming that I have the following table that lists a building manager's name, e-mail address and their building, is there a way that I can automate this to send these monthly e-mails from Outlook. Ideally this would be a click one button type of action:
1
4814
by: rn5a | last post by:
I have created a custom control button which when clicked displays a message in the JavaScript alert dialog. I could successfully compile the VB class file into a DLL & also could add it to the Toolbox in Visual Web Developer 2005 Express Edition but the alert message isn't popping up when I am implementing this control in an ASP.NET page & clicking the Button in the ASPX page. This is the class file: Imports System Imports System.Web...
1
3231
by: rn5a | last post by:
I want to create a custom control that encapsulates a Button & a TextBox. When the Button is clicked, the user is asked a question using JavaScript confirm (which shows 2 buttons - 'OK' & 'Cancel'). Till this point, no problem. Initially, the TextBox is empty. The Button has a property named 'ConfirmMessage' so that the developer using this custom control can modify the question in the confirm dialog. If the user clicks 'OK', I want the...
0
1393
by: rn5a | last post by:
A custom control is derived from the WebControl class & encapsulates a TextBox & a Button. When the Button is clicked, the user is shown the JavaScript confirm dialog with the 'OK' & 'Cancel' buttons. If the user clicks 'OK', the TextBox gets populated with 'true' & if 'Cancel' is clicked, the TextBox gets populated with 'false'. Note that when the user first comes to the ASPX page that uses this custom control, the TextBox is empty. This...
0
9663
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...
1
10136
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
9016
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7525
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6765
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5415
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
5548
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3695
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2906
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.