C + + file read and write detailed (Ofstream,ifstream,fstream) __c++

Source: Internet
Author: User
Tags control characters

Directory (?) [-] Validation of the status marker verification of state flags gets and sets the stream pointer get and put stream pointers binary cache and synchronization buffers and synchronization

In the view of C + + programming thought, each practice basically is uses ofstream,ifstream,fstream, before roughly knew its usage and the meaning, after saw several Daniel's Bowen, carries on the collation and the summary:


This is mainly about FStream:

[Java] view plain copy print? #include <fstream> ofstream//File write operation memory write storage device Ifstream//file read operation, storage device read area to memory FStream/ /Read and write operation, can read and write to open files

#include <fstream>
ofstream         //File write operation memory write to storage device 
ifstream         //file read operation, storage device read area to memory
FStream          

1. Open the file

In the FStream class, the member function open () implements the operation of opening a file, associating the data flow with the file, and reading and writing to the file through the Ofstream,ifstream,fstream object

Function: Open ()

[CPP] view plain copy print? <span style= "Font-family:times New Roman; Font-size:16px ' > Public member function void open (const char * filename, Ios_base::openmode mod E = Ios_base::in |      Ios_base::out); void Open (const wchar_t *_filename, Ios_base::openmode mode= ios_base::in | ios_base::out, int prot = Ios_base::_openprot); </SPAN>

Public member function

void open (const char * filename,
            ios_base::openmode mode = ios_base::in | ios_base::out) ;

void Open (const wchar_t *_filename,
ios_base::openmode mode= ios_base::in | ios_base::out,
int Pro t = Ios_base::_openprot);

Parameters: filename operation filename

Mode how to open a file

Prot Open File Properties//Basic rarely used, in view of the data, found that there are two ways

The way you open a file is defined in the iOS class (so the base class of streaming I/O), there are several ways:

Ios::in Open file for input (read)
Ios::out Open file for output (write)
Ios::ate Initial position: End of File
Ios::app All outputs are appended to the end of the file
Ios::trunc If the file already exists, delete the file first
Ios::binary Binary mode
These methods can be used in combination with the "or" Operation ("|"). ) in the way: for example [CPP]View Plain copy print?   Ofstream out; Out.open ("Hello.txt", ios::in|ios::out|ios::binary)//appropriate selection according to their needs
Ofstream out;
Out.open ("Hello.txt", ios::in|ios::out|ios::binary)                 //appropriate selection according to their needs
The properties of the open file are also defined in the iOS class:
0 Normal file, opening operation
1 Read-only files
2 Implied file
4 System files
The properties of the file can also be combined using the "or" operation and "+", which is not explained here.

In many programs, you may encounter ofstream out ("Hello.txt"), Ifstream in ("..."), FStream foi ("..."), and do not explicitly invoke the open () function to manipulate the file. The default open method is called directly, because the open () function is invoked in the constructor of the stream class and has the same constructor, so you can use the stream object directly to manipulate the file, by default, as follows:
[CPP] view plain copy print? <span style= "Font-family:times New Roman;   Font-size:16px "> Ofstream out (" ... ", ios::out);   Ifstream in ("...", ios::in);      FStream foi ("...", ios::in|ios::out); </SPAN>

Ofstream out ("...", ios::out);
Ifstream in ("...", ios::in);
FStream foi ("...", ios::in|ios::out);

When you use the default method to manipulate files, you can use the member function Is_open () to verify that the file is open

2. Close the file

When the file read and write operation is complete, we must close the file to make the file accessible again. The member function close (), which is responsible for emitting data from the cache and closing the file. Once this function is invoked, the original stream object can be used to open other files, and the file can be accessed again by other processes. To prevent the stream object from being destroyed, the open file is also contacted, and the destructor will automatically call close the closed function.


3. Reading and writing of text files

Class Ofstream, Ifstream and FStream are derived from Ostream, IStream and iostream respectively. This is why FStream objects can access data using members of their parent class.

In general, we will use these classes to input and output the same member functions (CIN and cout) that interact with the console (console). As shown in the following example, we use the overloaded insert operator <<:

[CPP] View Plain copy print?   // writing on a text file      #include  <fiostream.h >     int main  ()  {        ofstream out ( "OUT.txt");        if  (Out.is_open ())          {            out <<  "This  is a line.\n ";            out < <  "this is another line.\n";             out.close ();        }         return 0;    }  //Results:  written in OUT.txt:    this is a line.    this is another line   

     Writing on a-text file
    #include <fiostream.h>
    int main () {
        ofstream out ("OUT.txt");
        if (Out.is_open ()) 
       {out
            << ' This is a line.\n ';
            Out << ' This is another line.\n ';
            Out.close ();
        }
        return 0;
    }
   Result: Write in OUT.txt: This is
   a line.
   

Reading data from a file can also be used in the same way as cin>>:

[CPP] View Plain copy print?  reading a text file        #include  <iostream.h>         #include  <fstream.h>        #include  < Stdlib.h>             int main  ()  {           char buffer[256];           ifstream in ("test.txt");          if  ( ! in.is_open ())           { cout <<  " Error opening file "; exit  (1); }           while  (!in.eof ()  )           {               in.getline  (buffer,100);              cout << buffer <<  endl;          }           return 0;      }      //results   Output on the screen         This is a line.       this is  another line  

Reading a text file
    #include <iostream.h>
    #include <fstream.h>
    #include <stdlib.h>
    
    int main () {
        char buffer[256];
        Ifstream in ("test.txt");
        if (! In.is_open ())
        {cout << "Error opening file"; exit (1);}
        while (!in.eof ())
        {
            in.getline (buffer,100);
            cout << buffer << Endl;
        }
        return 0;
    }
    The result is the output of this are a line on the screen
     .
     This is another line

The example above reads the contents of a text file and then prints it to the screen. Note that we use a new member function called EOF, which is inherited from class iOS and returns True when the end of the file is reached. ifstream Validation of Status identifiers (verification of State flags)

In addition to EOF (), there are some member functions that verify the state of the stream (all return a bool return value): Bad ()

Returns true if an error occurs during the read and write process. For example, when we want to write to a file that is not open for write state, or if the device we are writing to has no space left. fail ()

Returns true except in the same case as bad (), and returns True when the format error is added, such as when you want to read an integer and get a letter. EOF ()

Returns true if the read file reaches the end of the file. Good ()

This is most common: This function returns False if any of the above functions return true.

To reset the status flags checked by the above member function, you can use the member function clear () with no parameters.
gets and sets the stream pointer (get and put stream pointers)

All input/output stream objects (I/O streams objects) have at least one flow pointer: Ifstream, similar to IStream, has a pointer called get pointer, pointing to the next element to be read. Ofstream, like Ostream, has a pointer put pointer that points to the location where the next element is written. FStream, similar to iostream, while inheriting get and put

We can read or configure these stream pointers to the read and write locations in the stream by using the following member functions: TELLG () and TELLP ()

This two member function returns the value of the Pos_type type (according to the ansi-c++ standard) without passing in the argument, which represents the position of the current get stream pointer (with TELLG) or the position of the put stream pointer (with TELLP). seekg () and SEEKP ()

This pair of functions is used to change the position of the stream pointer get and put respectively. Two functions are overloaded with two different prototypes: SEEKG (pos_type position);
SEEKP (pos_type position);

Using this prototype, the stream pointer is changed to point to an absolute position that is calculated from the start of the file. The parameter types passed in require the same type of return value as the function Tellg and TELLP. SEEKG (off_type offset, seekdir direction);
SEEKP (off_type offset, seekdir direction);

Use this prototype to specify a displacement (offset) to be computed by a specific pointer that is determined by the parameter direction. It can be:

Ios::beg Displacement calculated from the start position of the stream
Ios::cur The displacement calculated from the current position of the stream pointer
Ios::end Displacements from the end of the stream

The flow pointer get and put values are different for the text file and the binary (binary file) calculation because some special characters in the text-mode file may be modified. For this reason, it is recommended that files opened in text file mode always use the first prototype of SEEKG and SEEKP, and do not modify the return values of TELLG or TELLP. For binary files, you can use these functions arbitrarily, and there should be no unexpected behavior.

The following examples use these functions to obtain the size of a binary file:

[CPP] View Plain copy print?  obtaining file size        #include  <iostream.h>         #include  <fstream.h>              const char * filename =  "Test.txt";            int main  ()  {          long  l,m;          ifstream in (filename, ios::in|ios::binary) ;          l = in.tellg ();           in.seekg  (0, ios::end);          &NBSP;M&NBSP;=&NBSP;IN.TELLG ();          in.close ();          cout <<  "size of " &NBSP;&Lt;< filename;          cout <<  " is    <<  (m-l)  <<  " bytes.\n";           return 0;      }           //results:      size of example.txt is 40 bytes.  

Obtaining file size
    #include <iostream.h>
    #include <fstream.h>
    
    const char * filename = " Test.txt ";
    
    int main () {
        long l,m;
        Ifstream in (filename, ios::in|ios::binary);
        L = In.tellg ();
        IN.SEEKG (0, ios::end);
        m = In.tellg ();
        In.close ();
        cout << "size of" << filename;
        cout << "is" << (m-l) << "bytes.\n";
        return 0;
    }
   
   Result: The
   size of Example.txt is bytes.


4. binary Files

In binary files, the use of << and >>, and functions (such as getline) for operator input and output data, have no practical significance, although they are grammatically compliant.

The file stream includes two member functions that are specially designed for sequential read-write data: Write and read. The first function (write) is a member function of the ostream, which is inherited by Ofstream. And read is a member function of IStream, inherited by Ifstream. The FStream object of the class has both functions. Their prototype is: Write (char * buffer, streamsize size);
Read (char * buffer, streamsize size);

Here the buffer is a memory address that is used to store or read the data. The parameter size is an integer value that represents the number of characters to read out or write from the cache (buffer).

[CPP] View Plain copy print?  reading binary file         #include  <iostream>          #include  <fstream.h>               const char * filename =  "Test.txt";               int main  ()  {            char * buffer;            long size;           ifstream in  ( filename, ios::in|ios::binary|ios::ate);           size &NBSP;=&NBSP;IN.TELLG ();           in.seekg  (0, ios :: Beg);           buffer = new char [size];           in.read  (buffer, size);            in.close ();                       cout <<  " The complete file is in a buffer ";                       delete[] buffer;            return 0;       }        //operation results:        the complete file  is in a buffer  

Reading binary file
    #include <iostream>
    #include <fstream.h>
    
    const char * filename = " Test.txt ";
    
    int main () {
        char * buffer;
        Long size;
        Ifstream in (filename, ios::in|ios::binary|ios::ate);
        Size = In.tellg ();
        IN.SEEKG (0, Ios::beg);
        buffer = new char [size];
        In.read (buffer, size);
        In.close ();
        
        cout << "The complete file is in a buffer";
        
        delete[] buffer;
        return 0;
    }
    Run Result: The
    complete file is in a buffer

5. Caching and synchronization (buffers and synchronization)

When we operate on file streams, they are associated with a streambuf type of cache (buffer). This cache (buffer) is actually a piece of memory space, as a medium for streaming (stream) and physical files. For example, for an output stream, every time a member function is put (write a single character) called, the character is not directly written to the corresponding physical file of the output stream, but is first inserted into the cache (buffer) of the stream.

When the cache is emitted (flush), all data inside it is either written to the physical medium (if it is an output stream), or simply erased (if it is an input stream). This process, called Synchronization (synchronization), occurs in any of the following situations: When a file is closed: all caches that have not been fully written out or read are synchronized until the file is closed. when the cache buffer is full: The cache buffers has a certain space limit. When the cache is full, it is automatically synchronized. The control character explicitly indicates that synchronization occurs when some specific control characters in the stream are encountered. These control characters include: Flush and Endl. explicitly invoke function sync (): calling member function sync () (without parameters) can cause immediate synchronization. This function returns an int value equal to 1 that indicates that the stream has no associated cache or operation failed.

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.