Redirect the stream buffer of cout to a file with ios: rdbuf

Source: Internet
Author: User
Tags traits

Introduction:
• This article mainly about how to use ios: rdbuf () function redirect the standard output stream to a file, that is, redirect the cout output stream.
• Two questions will be answered in this article: 1.how to redirect a stream. 2. what is the real face of cout, cin and cerr.
Many times, for some special purposes, we will involve the issue of outputting redirection to the console. For example, when writing a GUI program and debugging convenience, we need to output some intermediate results, however, if MessageBox is used,
It is really unsatisfactory. It is really hard to get a string together, but if we want to output a value or address, we have to create a CString object to format them into a string and output it with MessageBox! Of course everyone's
Debugging methods are different. This article mainly describes how to redirect the cout output stream to other places, such as a file. Of course, if you want to output some debugging data to a file through cout in your GUI project, or
Using cout to write logs directly, this article will be helpful to you. Secondly, if you understand redirection and technology, you will get to know some old friends, such as cout and cin, the real identity of cerr.
First, we will introduce a very important member of the basic_ios class, which is ios: rdbuf (). Let's take a look at the definition of this function (vs2008 ):
Typedef basic_streambuf <_ Elem, _ Traits> _ Mysb;
_ Mysb * rdbuf () const
{// Return stream buffer pointer
Return (_ Mystrbuf );
}
_ Mysb * rdbuf (_ Mysb * _ Strbuf)
{// Set stream buffer pointer
_ Mysb * _ Oldstrbuf = _ Mystrbuf;
_ Mystrbuf = _ Strbuf;
Clear ();
Return (_ Oldstrbuf );
}
It is not hard to see that the rdbuf () function sets and modifies the io stream pointer. For this reason, I think whether I can redirect the input and output by modifying the buffer pointer associated with the io class, of course the truth is optimistic. For example
Operation. First, redirect the cout output to a file and use the following code:
Ofstream dwout ("redire.txt .txt ");
Ofstream: _ Mysb * org_cout = cout. rdbuf (dwout. rdbuf ());
In this way, the cout output buffer stream is successfully redirected to the "redirection.txt" file instead of the console. Of course, we should save the original stream pointer to org_cout, used to restore the cout stream buffer. Next
We can do this:
For (int I = 0; I <5; I ++)
{
Cout <"redirection ";
}
Input five "redirection" to "redire.txt .txt" and output them to the file instead of the console. Next, open the "redire.txt .txt" file and output the file content to the screen. Therefore, we must first restore the cout stream to make it
The output is restored to the console and then verified whether our redirection is successful. The Code is as follows:
Dwin. open ("redire.txt .txt ");
Cout <dwin. rdbuf (); // This statement can directly output all the content of "redire.txt .txt", which is another powerful function of rdbuf.
The following is the complete verification code. The first time you open the file, write five "duwen" and the output is to verify the cout <file. rdbuf () can output all the content of the file at one time, followed by redirection cout, and then write five cout
"Redirection", and then restore the cout stream to output the file content to the console. Because the default open mode is the default out, the second time you open the file (cout) the file content will be cleared first, that is, the five "duwen" will be cleared, so
After the second display, only five "redirection" are displayed ":

/*************************************** *********************************
Description: Redirect the cout stream.
Notices: Copyright (c) Duwen
TIME: Post time: 5/11/2012, write time: 6/3/2011
**************************************** ********************************/

# Include "stdafx. h"
# Include <iostream>
# Include <fstream>
Using namespace std;

Int _ tmain (int argc, _ TCHAR * argv [])
{
// Create a redirection file, and write 10 "duwen" in.

Ofstream dwout ("redire.txt .txt ");
For (int I = 0; I <5; I ++)
{
Dwout <"duwen ";
}
Dwout <'\ n ';
Dwout. close ();

// Output the file contents
Ifstream dwin ("redire.txt .txt ");
Cout <dwin. rdbuf (); // Note: this sentence can output whole file
Dwin. close ();

// Open "redire.txt .txt", we'll redirect the stream buffer of "cout" latter.
Dwout. open ("redire.txt .txt ");
// Redirect
Ofstream: _ Mysb * org_cout = cout. rdbuf (dwout. rdbuf ());
For (int I = 0; I <5; I ++)
{
// We output 5 "redirection" which cannot be shown on console, instead, it will be redirected to "redire.txt .txt ".
Cout <"redirection ";
}
Dwout. close ();
// Open redirection.txt.
Dwin. open ("redire.txt .txt ");
// Recover the stream buffer of cout, that is, console
Cout. rdbuf (org_cout );

// Verify if our redirection succeeded.
Cout <dwin. rdbuf ();
Cout <endl;
// Note: we mustn't close all the files we have opened, because the destructor of each file class did it automatically.
Return 0;
}
Well, with the above understanding, can you still think of anything? exploration will never stop.
When I first started to learn C ++, I was always curious about cout, cin, and cerr. The book says they are all global stream objects. Take cout as an example, the book says it is the object of ostream, but I tried to create my "cout" in ostream myout
The compiler will not allow this. Of course, the first reason I can think of is that ostream does not have such a no-argument constructor. So I open the ostream document, which contains two constructor functions, as shown below:

Explicit basic_ostream (basic_streambuf <_ Elem, _ Traits> * _ Strbuf, bool _ Isstd = false)
 
Basic_ostream (_ Uninitialized, bool _ Addit = true)

 
But at that time, I still couldn't understand the meaning of this statement, so I wanted to see the definition of cout, So I clicked cout-to go to the definition, the obtained result is _ PURE_APPDOMAIN_GLOBAL extern _ CRTDATA2 ostream cout. Then I searched the entire ostream file but still couldn't find it. I said it was a global object, but I couldn't find it, I really want to hide my face, and I couldn't help it. At that time, I used a work und to create my myout. How did I do it? You guess, huh, huh, let's get down to the truth. in fact, when I found it, I came up with an idea. I carefully read the code above. I first created a file and then redirected the cout stream to the file, let's take a look at the first constructor of ostream. I smiled. Did you think of it... the following code is provided:
// My cout
Ofstream console (stdout );
Ostream mycout (console. rdbuf ());
// My cin
Ifstream input (stdin );
Ostream myin (input. rdbuf ());
// My cerr
Ofstream error (stderr );
Ostream mycerr (error. rdbuf ());
Well, this article should also be written here. It should be noted that, in the io class family, all other types except the ios_base class can be redirected using rdbuf, not limited to cout, this document is just an example. in addition, redirection can be used to conveniently implement many other functions,
For example, if you use a cin statement to input and write files on the keyboard, the reader should be able to draw a line from each other. Finally, if you copy and reprint the statement, please indicate the original author, please support the original.
 

 

Excerpted from building a high-end server without sand float

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.