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

Source: Internet
Author: User
Tags c ifstream

In the process of writing code, the most common thing we do is IO operations, whether it is the console or the file. But forget to write code for a while, here's a look at the specific classes and operations of the C + + standard I/O library.

The standard I/O library for C + + includes the iostream,fstream we use frequently, and the less frequently used stringstream. The first two are I/O operations to the console and files, and StringStream can use I/O operations to format the data in memory. Standard I/O operations in C + + are more concise, secure, and less efficient to perform than C.


standard I/O Library class inheritance system

For programming languages, conceptually, reading data from control terminals, disk files, and memory should not affect I/O operations, C + + in order to solve the character stream that supports different devices, through object-oriented thinking (nonsense, you do not have this idea, you are what C + +), through inheritance to implement a set of classes, Processing the control terminal, disk files, as well as the memory data of I/O operation, is quoted Cplusplus official website on the input and output stream class inheritance system diagram, I drew a bit, as follows:

As can be known, the base class for I/O operations is ios_base, and 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 read data from a file, derived from IStream
  • Ofstream write data to a file, derived from Ostream
  • FStream read-write file, derived from iostream
  • <sstream>
  • Istringstream Read 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 the I/O system defines the basic flow format flags (hex, DEC, etc.), the file open mode (in, out, bin, etc.), the status flag of the stream (failbit, etc.), and the related functions, as follows in Linux/usr/include/c++/ The enumeration definitions for these flags in 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

To better manage I/O operations, the standard defines a series of conditional status flags and functions to manage flow objects, such as availability and errors. The status flag for a stream is defined in the Ios_base class, so the flow's status flag management 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 the Ios_base, as follows:

    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

You can test the status flags simply by using the following code:

#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;}
After entering 1 A, the following is displayed:

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 ifstream and Ofstream classes responsible for file I/O read and write operations, class FStream responsible for file read and write, the 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;

The specific meanings are as follows:

    • Ios_base::in read-only Open
    • Ios_base::out only Write Open
    • Ios_base::app move to the end of the file before each write
    • Ios_base::ate immediately after opening the file to the end of 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, open by default in, Ofstream, open by default | Trunc,fstream is default with in | Out mode open. If you want to open a file with Ofstream and save the file's data at the same time, you can only open the mode by displaying the specified app. 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)

If the FStream open method is out, the data in the file is also emptied. When the file is opened out (without 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 that can extract data from built-in data types, such as input operators >> Used to extract data from the stream buffer streambuf and output it to a variable of a specific type, such as the IStream header file, specifically defined as follows:

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 also supports input and output operations on file stream filebuf. For example, the following example reads data from a file by using the input 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 you can support this 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 deal with parsing data by row, and the IStream class defines the Getline member function to support the extraction of data that is fixed or separated by a specific delimiter in a particular size or delimiter (the default is a newline character). Similarly, the string header file also provides the Getline global function, which supports extracting data from the IStream class with a specific size or delimiter (the default is a newline character). Defined as follows:

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 defaults to a newline//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 Default to NewLine

Use 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 the SEEKG and TELLG of the full contents of the file

In order to efficiently operate files, we often use the location function of the file stream, and in the Ios_base class, we define the following members.

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

TELLP and SEEKP, defined in IStream, are defined in TELLG and Seekg,ostream, respectively, to obtain the location of the file stream where the current operation resides, and to locate the file stream operation. This is done by the 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, since the end of the file has been positioned, so is the file stream size        is.seekg (0, Is.beg);       Reposition 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, defines the Istringstream in the Sstream header file,Ostringstream,StringStream, you can perform I/O operations simply by binding the stream to the memory string object. The above three I/O classes are used to read a memory string object into a specified object, writes data from 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 said the standard input and output operations defined in IStream and ostream, derived relationships, for the Istringstream,ostringstream can also be used for 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). Common operations 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

The specific use is as follows:

#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; Reads data from the stream into the object (with whitespace as a delimiter)    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;}


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.