C ++ file stream operations and stream buffer redirection

Source: Internet
Author: User
Tags traits
1 # Include <iostream>
2 # Include <fstream>
3 # Include <cassert>
4
5 Using Namespace STD;
6 Int Main ()
7 {
8 Ifstream In ( " Test.txt " );
9 Assert ( In . Is_open ());
10
11 // The base address is the end of the file, and the offset address is 0, so the pointer is located at the end of the file.
12 In . Seekg ( 0 , IOS: End );
13 // SP is the positioning pointer, because it is at the end of the file, so it is the file size
14 Streampos sp = In . Tellg ();
15 Cout < " File Size: " <Endl <sp <Endl;
16
17 // The base address is the end of the file, and the offset address is negative, so forward the SP/3 bytes
18 In . Seekg (-SP/ 3 , IOS: End );
19 Streampos SP2 = In . Tellg ();
20 Cout < " From file to point: " <Endl <SP2 <Endl;
21
22 // The base address is the file header, and the offset is 0, so the file is located in the file header; the file content is read from the beginning
23 In . Seekg ( 0 , IOS: Beg );
24 Cout < In . Rdbuf () <Endl;
25
26 // Read File Content from SP2
27 In . Seekg (SP2 );
28 Cout < In . Rdbuf () <Endl;
29
30 In . Close ();
31
32 Return 0 ;
33 }

 

 1 # Include <iostream>
2 # Include <fstream>
3 # Include <cassert>
4 # Include <streambuf>
5
6 Int Main ( Void )
7 {
8 STD: ofstream log ( " Test.txt " );
9 Assert (log. is_open ());
10
11 // Returns the original cout stream buffer pointer to redirect the cout to the log file stream buffer.
12 STD: streambuf * x = STD: cout. rdbuf (log. rdbuf ());
13
14 // Write to file
15 STD: cout <" Xiaolouyiyetingchunyu \ n " ;
16
17 Log. Close ();
18
19 STD: cout. rdbuf (X ); // Restore the cout Stream Object Pointer
20
21 STD: cout < " Yuanyuewandao \ n " ; // Write cout
22
23 Return 0 ;
24 }

When we use STL programming, we sometimes think of outputting the content pointed to by a stream object with another stream object. For example, we want to output the content of a file to the display, we can use two simple linesCodeYou can do this.

Ifstream infile ("test.txt ");

Cout <infile. rdbuf ();

The exported code redirects the streams in the infilestream object to the standard output cout. you can view the content of test.txt on the screen.

The following example is from msdn, which clearly describes how to use the rdbuf function.

 
// Basic_ios_rdbuf.cpp // compile with:/ehs# include <IOS> # include <iostream> # include <fstream> int main () {using namespace STD; ofstream file ("rdbuf.txt"); streambuf * x = cout. rdbuf (file. rdbuf (); cout <"test" <Endl; // goes to file cout. rdbuf (x); cout <"Test2" <Endl ;}

The rdbuf function can be called in two ways.

 
Basic_Streambuf <ELEM, traits> * rdbuf () const;
Basic_Streambuf <ELEM, traits> * rdbuf (Basic_Streambuf <E, T> *_ Sb);

1) No parameters. Returns the buffer pointer of the caller.

2) The parameter is a stream buffer pointer. It associates the caller with the parameter (stream buffer pointer) and returns the currently associated stream buffer pointer.

If we use C to write a file copyProgramFor example, for an MP3 file, we first consider the file input and output function in C language. The idea is to create a buffer with a specified size. We read the data of the buffer size cyclically from the source file, then write it into the target file. In C ++, we discard the byte replication method using the character buffer, because this method looks cumbersome and inefficient at all. The following two methods can be compared (the program can be executed directly ):

C:

# Include <stdlib. h>
# Include <stdio. h>
Int main ()
{
Char Buf [256];
File * pf1, * pf2;
If (pf1 = fopen ("1.mp3", "rb") = NULL)
{
Printf ("failed to open the source file/N ");
Return 0;
}
If (pf2 = fopen ("2.mp3", "WB") = NULL)
{
Printf ("failed to open the target file/N ");
Return 0;
}
While (fread (BUF, 1,256, pf1 ),! Feof (pf1 ))
{
Fwrite (BUF, 1,256, pf2 );
}
Fclose (pf1 );
Fclose (pf2 );
Return 0;

}

In C ++:

# Include <fstream>
# Include <iostream>
Using namespace STD;
Int main ()
{
Fstream fin ("1.mp3", IOS: In | IOs: Binary );
If (! Fin. is_open ())
{
Cout <"failed to open source file" <Endl;
Return 0;
}
Fstream fout ("2.mp3", IOS: Out | IOs: Binary );
If (! Fin. is_open ())
{
Cout <"failed to open the target file! "<Endl;
Return 0;
}
Fout <fin. rdbuf ();
Fin. Close ();
Fout. Close ();
Return 0;
}

Does it seem much clearer? This is the power of the stream buffer in C ++. The program redirects the source file stream to the stream object associated with the target file, use fout <fin. rdbuf (); a piece of code completes the function of circular read/write buffer in C language, and uses the underlying stream buffer in C ++, which is more efficient!

Related Article

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.