C + + standard I/O library: iostream, FStream, Sstringstream

Source: Internet
Author: User
Tags c ifstream

In the process of writing the code. The most common thing we do is IO operations, whether it's the console or the file. But forget about the code for a while, here's a detailed class and operation for the C + + standard I/O library.

The standard I/O library for C + + contains the Iostream,fstream we often use. And the less often used stringstream. The first two are I/O operations to the console and files, and StringStream is able to format the data in memory using I/O operations.

C + + 's standard I/O operations are more concise, secure, and less efficient than C.

standard I/O Library class inheritance system

In the case of programming languages, the concept of reading data from control terminals, disk files, and in-memory should not affect I/O operations. C + + To resolve character streams that support different devices. Through object-oriented thinking (nonsense, you don't have to use this idea, you're still what C + +). Through inheritance to implement a set of classes, respectively, the control terminal, disk files, as well as memory data I/O operations, is quoted Cplusplus official website on the input and output stream class inheritance system diagram, I drew a bit, such as the following:

By being able to know that the base class for I/O operations is ios_base, the purpose of each class is as follows:

  • <iostream>
  • IStream reading data from the stream
  • Ostream writing data to the stream
  • iostream convection for read and write operations. Derived from IStream and ostream
  • <fstream>
  • Ifstream reads data from a file. derived from IStream
  • Ofstream writes data to a file, derived from Ostream
  • FStream read-write file, derived from iostream
  • <sstream>
  • Istringstream reads a string object. derived from IStream
  • Ostringstream writes a String object. derived from Ostream
  • StringStream read-Write String object, derived from iostream

The C + + standard for I/O architecture defines the main stream format flags (hex, DEC, etc.), the file open mode (in, out, bin, etc.), the status flag of the stream (Failbit, etc.). and related functions, such as the following enumeration definitions for these flags in Linux under/usr/include/c++/4.6/bits/ios_base.h:

    • Stream Format Flags

Enum _ios_fmtflags     {       _s_boolalpha      = 1L << 0,      _s_dec            = 1L << 1,      _s_fixed          = 1L << 2,      _s_hex            = 1L << 3,      _s_internal       = 1L << 4,      _s_left           = 1L << 5,
   _s_oct            = 1L << 6,      _s_right          = 1L << 7,      _s_scientific     = 1L << 8,      _s_ Showbase       = 1L << 9,      _s_showpoint      = 1L << ten,      _s_showpos        = 1L << One,      _s_ SKIPWS         = 1L <<,      _s_unitbuf        = 1L <<,      _s_uppercase      = 1L <<      _s_ Adjustfield    = _s_left | _s_right | _s_internal,      _s_basefield      = _s_dec | _s_oct | _s_hex,      _s_ Floatfield     = _s_scientific | _s_fixed,      _s_ios_fmtflags_end = 1L <<     ;

    • File open mode

Enum _ios_openmode     {       _s_app            = 1L << 0,      _s_ate            = 1L << 1,      _s_bin            = 1L << 2,      _s_in             = 1L << 3,      _s_out            = 1L << 4,      _s_trunc          = 1L << 5,      _s_ios_ Openmode_end = 1L <<     ;

    • Status Flag of the stream

Enum _ios_iostate    {       _s_goodbit                = 0,      _s_badbit                 = 1L << 0,      _s_eofbit                 = 1L < < 1,      _s_failbit                = 1L << 2,      _s_ios_iostate_end = 1L << +     };

Status of the I/O stream

For better management of I/O operations. The standard defines a series of conditional state flags and functions for managing flow objects. For example, whether it is available, and what errors occur.

The status flags for a stream are defined in the Ios_base class. So the status flag management of the flow applies to the terminal, file, and string stream objects. The status of the stream is defined as: ios_base::iostate, which values are defined in ios_base, such as the following:

    typedef _ios_iostate Iostate;    static const iostate Badbit =_s_badbit;    The stream is broken (the problem with the stream itself)    static const iostate eofbit =_s_eofbit;    The stream has reached the end of the    static const iostate failbit =_s_failbit;   I/O failure (logic problem on the operation itself)    static const iostate goodbit =_s_goodbit;   Good flow ... Normal
To manage the status flags described above, the standard provides the following functions for processing in the iOS class:

Iostate  rdstate () const                     //return stream condition State void Clear (iostate __state = goodbit);       Sets the condition state of the stream, which is set to normal void SetState (Iostate __state) by default;              Sets the state of the stream, and the clear difference: does not clear the other flag bool Good () const           //stream is normal bool EOF () const            //Stream whether to end bool fail () const           //Stream whether i/ O failed bool Bad () const            //stream is corrupted

The ability to test the status flag with the following code is simple:

#include <iostream>using std::cout;using std::cin;using std::endl;int Main () {    int A;    cin>>a;    cout<< "Goodbit:" <<cin.good () << "Eofbit:" <<cin.eof () << "Failbit:" <<cin.fail () << "Badbit:" <<cin.bad () <<endl;        cin>>a;    cout<< "Goodbit:" <<cin.good () << "Eofbit:" <<cin.eof () << "Failbit:" <<cin.fail () << "Badbit:" <<cin.bad () <<endl;}
Enter 1 A after display demo sample For example the following:

1goodbit:1 eofbit:0 failbit:0 badbit:0agoodbit:0 eofbit:0 failbit:1 badbit:0

From the above, illegal input causes I/O to fail, and the Failbit stream flag takes effect.

File I/O operations

C + + provides read and write operations for file I/O for the Ifstream and Ofstream classes. The FStream class is responsible for reading and writing files. An inheritance relationship is described at the beginning of the article.

As stated earlier, the file open mode is defined in the Ios_base base class.

typedef _ios_openmode openmode;///seek to end before each write.static const OpenMode app =         _s_app;///Open and seek To end immediately after opening.static const OpenMode ate =         _s_ate;///Perform input and output in binary mode (as Op posed to text mode). static const OpenMode binary =      _s_bin;///Open for input.  Default for @c ifstream and fstream.static const OpenMode in =          _s_in;///Open for output.  Default for @c ofstream and fstream.static const OpenMode out =         _s_out;///Open for input.  Default for @c ofstream.static const OpenMode trunc =       _s_trunc;

Detailed meanings such as the following:

    • Ios_base::in Just read Open
    • Ios_base::out Just write Open
    • Ios_base::app move to the end of the file before each write
    • Ios_base::ate to the end of file immediately after opening the file
    • Ios_base::trunc opening a file and emptying the file stream
    • Ios_base::binary Read and write operations in binary mode

Open the file in Ifstream mode by default. Open in Ofstream mode, default open mode is out | Trunc FStream is default with in | Out mode open. Suppose you want to open a file with Ofstream. and save the file data at the same time. You can only open the mode by displaying the specified app.

For example, the following is the open function prototype in the FStream header file:

Ifstreamvoid Open (const char* __s, Ios_base::openmode __mode = ios_base::in) ofstreamvoid open (const char* __s, Ios_base:: OpenMode __mode = Ios_base::out | Ios_base::trunc) fstreamvoid Open (const char* __s, Ios_base::openmode __mode = ios_base::in | ios_base::out)

Assuming the fstream is open, the data in the file is also emptied.

When a file is opened out (not including in mode), a new file is created if the file does not exist.

    • Input and output operators

The Istream,ostream class defines an algorithm extractor for input and output (arithmetic Extractor): ' >> ' and ' << ' operators to extract data from built-in data types, such as input operators >> Used to extract data from the stream buffer streambuf. and output to a specific type of variable, such as the IStream header file in detail defined such as the following:

Class, used to extract __istream_type& operator>> (bool& __n);__istream_type& operator>> (short& __ N);__istream_type& operator>> (unsigned short& __n);__istream_type& operator>> (int& __n) ;__istream_type& operator>> (unsigned int& __n);     __istream_type& operator>> (long& __n); __istream_type& operator>> (unsigned long& __n);__istream_type& operator>> (Long long& __n );__istream_type& operator>> (unsigned long long& __n);__istream_type& operator>> (float& __f) __istream_type& operator>> (double& __f) __istream_type& operator>> (Long double& __f) __istream_type& operator>> (void*& __p)//out-of-class definition for extracting characters Template<class _traits> inline Basic_ Istream<char, _traits>&operator>> (Basic_istream<char, _traits>& __in, unsigned char& _ _c); Template<class _traits>inline Basic_istream<char, _traits>&oPerator>> (Basic_istream<char, _traits>& __in, signed char& __c); Template<class _Traits> Inline Basic_istream<char, _traits>&operator>> (Basic_istream<char, _traits>& __in, unsigned char* __s); Template<class _traits>inline Basic_istream<char, _traits>&operator>> ( Basic_istream<char, _traits>& __in, signed char* __s), overloads of the//string class for input and output operator, Enables it to support string type input and output Template<typename _chart, TypeName _traits, TypeName _alloc>basic_istream<_chart, _traits >&operator>> (Basic_istream<_chart, _traits>& __is,       Basic_string<_chart, _traits, _alloc>& __str); Template<typename _chart, TypeName _Traits, TypeName _Alloc >inline Basic_ostream<_chart, _traits>&operator<< (Basic_ostream<_chart, _Traits>& __ os,       Const Basic_string<_chart, _traits, _alloc>& __str)

Because Ifstream and ofstream are derived from IStream and ostream, FStream supports input and output operations on file stream Filebuf as well. The ratio reads the data in the file via the input and output operator:

#include <iostream> #include <fstream> #include <string>using namespace Std;int main () {    string FileName = "Test.txt";    Ofstream outopt (Filename.c_str (),  ios_base::out | ios_base::trunc);    if (!outopt)    {cout<<filename<< "Open failed ..." <<endl;return-1;    }    outopt<< "1 2 3 Test text";    Outopt.close ();    int a[3];    String b[2];    Ifstream inopt (Filename.c_str ());    inopt>>a[0]>>a[1]>>a[2];    Reads three integers from the file buffer, separated by a whitespace character    inopt>>b[0]>>b[1];    Reads two string data from a file buffer separated by whitespace (string type operator << class overload, so it can support the operation)    cout<<a[0]<< ' << a[1]<< ' <<a[2]<<endl;       cout<<b[0]<< ' <<b[1]<<endl;        Inopt.close ();    return 0;}

    • Getline operation

In the process of file I/O, we often have to deal with the data by row analysis processing. The Getline member function is defined within the IStream class to support the extraction of data that is fixed or separated by a specific delimiter with a specific size or delimiter (the default feeling of a newline character). Similarly, the string header file also provides the Getline global function, supported from the IStream class. Extracts the data with a specific size or delimiter (the default is a line break). Definitions such as the following:

Defined within the IStream class that provides reading a row of data from the input stream into the char* __istream_type&getline (char_type* __s, Streamsize __n, Char_type __delim);// Delim the//string header file definition (actually in basic_string.h), providing a row of data read from the input stream into a string Template<typename _chart, TypeName _traits, TypeName _alloc>basic_istream<_chart, _traits>&getline (Basic_istream<_chart, _Traits>& __is ,    Basic_string<_chart, _traits, _alloc>& __str, _chart __delim);//delim the feeling of a newline

Use for example the following:

#include <iostream> #include <fstream> #include <string>using namespace Std;int main () {    ifstream InFile ("test.txt");    if (!infile)    {        cout<< "open Test.txt failed ..." <<endl;        return-1;    }        Char str1[256] = "";    Infile.getline (str1, 255, ' \ n ');    String str2;    Getline (InFile, str2);        cout<<str1<<endl;    Cout<<str2<<endl;}

    • Get seekg and Tellg of all the contents of a file

File stream positioning is often used for efficient file operation. In the Ios_base class. Defines a member such as the following,

typedef _ios_seekdir Seekdir;static Const Seekdir beg =          _s_beg;    The file stream begins with static const Seekdir cur =          _s_cur;    The location of the current file stream is static const Seekdir end =          _s_end;   File Stream Trailer

TELLG and SEEKG are defined in IStream. TELLP and SEEKP are defined in Ostream, respectively, to obtain the location of the file stream where the current operation resides and to locate the file stream operation. For example, the following is a seek operation to read the contents of the entire file into memory:

#include <iostream> #include <fstream>int main () {    std::ifstream is ("Test.txt", std::ios_base::binary );    if (IS)    {        //Get File size        is.seekg (0,  std::ios_base::end);   Navigate to end of file        int length = IS.TELLG ();    Gets the location of the current file stream, because the end of the file has been located, so is the file stream size        is.seekg (0, Is.beg);       Again position pos to file stream start        char * buffer = new char [length];        Is.read (buffer,length);        Is.close ();        Output to screen        std::cout.write (buffer,length);        Delete[]  buffer;    return 0;}
I/O operations for memory data
The C + + I/o Standard library supports the I/O operation of memory data, defined in the Sstream header fileIstringstream,ostringstream. StringStream, the only need to bind the stream to a memory string object is the ability to perform I/O operations. The above three I/O classes are used to read a memory string object into a specified objectWrites the data in the specified object to a string object. StringStream can be used to read and write String objects。

In the above I/O file Operations Section has already described the standard input and output operations defined in IStream and ostream, as derived relationships know that for istringstream,ostringstream the same can be done with standard input and output operations, operate on the stringbuf of the StringStream (similar to the filebuf of the iostream Streambuf,fstream, which is not described here). The operations commonly used for the StringStream class are as follows:

StringStream SS (MYSTR)//Create SS object, stream stream to hold data of string type MyStr, SS.STR ()//Return data in SS stream, return type is String type SS.STR (MYSTR)// To set the contents of the SS stream to mystr data

Use details such as the following:

#include <iostream> #include <sstream> #include <string>using namespace Std;int main () {    Istringstream IStream;    Istream.str ("1 2 3 Hello");        int A, B, C;    string str1;    istream>>a>>b>>c>>str1; Reading data from a stream into an object (with a blank character)    cout<<a<< ' <<b<< ' <<c<< ' <<str1<< Endl;        Ostringstream ostream;    ostream<<a<< ' <<b<< ' <<c<< ' <<str1; Writes data to the stream        string out = Ostream.str ();    Cout<<out<<endl;}

C + + standard I/O library: iostream, FStream, Sstringstream

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.