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

Source: Internet
Author: User

In the view of C + + programming ideas, each exercise is basically using ofstream,ifstream,fstream, before a rough knowledge of its usage and meaning, after reading a few Daniel's blog post, to organize and summarize:

Here is the main discussion of fstream content:

[Java]View Plaincopyprint?
    1. #include <fstream>
    2. Ofstream //File write operation memory write to storage device
    3. Ifstream //file read operation, storage device read-in into memory
    4. FStream //Read and write operations, read and write to open files

1. Open File

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

Function: Open ()

[CPP]View Plaincopyprint?
  1. <span style="Font-family:times New roman;font-size:16px;" >
  2. Public member function
  3. VOID Open ( const char * filename,
  4. Ios_base::openmode mode = Ios_base::in | Ios_base::out);
  5. VOID Open (const wchar_t *_filename,
  6. Ios_base::openmode mode= Ios_base::in | Ios_base::out,
  7. int prot = Ios_base::_openprot);
  8. </span>

Parameter: FileName Action file name

Mode how to open a file

Prot Open File Properties//Basic rarely used, when viewing the data, found that there are two ways

The way you open a file is defined in the iOS class (so the base class for streaming I/O) in the following ways:

Ios::in Open a file for input (read)
Ios::out Open file for output (write)
Ios::ate Initial position: End of File
Ios::app All outputs appended to the end of the file
Ios::trunc If the file already exists, delete the file first
Ios::binary Binary mode

These methods are able to be used in combination with the "or" Operation ("|" ) In such a way that:

[CPP]View Plaincopyprint?
    1. Ofstream out;
    2. Out.open ("Hello.txt", ios::in|ios::out|ios::binary) //appropriate selection according to your needs

The properties of the open file are also defined in the iOS class:

0 Normal file, open 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.

Many programs, may encounter ofstream out ("Hello.txt"), Ifstream in ("..."), FStream foi ("...") such use, and do not explicitly go to call the open () function to do the file operation, The default opening method is called directly, because the open () function is called in the constructor of the stream class and has the same constructor, so here you can use the stream object directly for the file operation, as follows:

[CPP]View Plaincopyprint?
    1. <span style="Font-family:times New roman;font-size:16px;" >
    2. Ofstream out ("...", ios::out);
    3. Ifstream in ("...", ios::in);
    4. FStream foi ("...", ios::in|ios::out);
    5. </span>

You can use the member function Is_open () to verify that a file is open when you use the default method for file manipulation

2. Close the file

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

3. Reading and writing text files

Class Ofstream, Ifstream and FStream are derived from Ostream, IStream and iostream respectively. This is why the FStream object can use the members of its parent class to access the data.

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

[CPP]View Plaincopyprint?
  1. //Writing on a text file
  2. #include <fiostream.h>
  3. int main () {
  4. Ofstream out ("OUT.txt");
  5. if (Out.is_open ())
  6. {
  7. Out << ' This is a line.\n ';
  8. Out << ' This is another line.\n ';
  9. Out.close ();
  10. }
  11. return 0;
  12. }
  13. Result: Write in OUT.txt:
  14. This was a line.
  15. This was another line

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

[CPP]View Plaincopyprint?
  1. Reading a text file
  2. #include <iostream.h>
  3. #include <fstream.h>
  4. #include <stdlib.h>
  5. int main () {
  6. Char buffer[256];
  7. Ifstream in ("test.txt");
  8. if (! In.is_open ())
  9. {cout << "Error opening file"; exit (1);}
  10. While (!in.eof ())
  11. {
  12. In.getline (buffer,100);
  13. cout << buffer << Endl;
  14. }
  15. return 0;
  16. }
  17. //Results output on the screen
  18. This was a line.
  19. This was another line

The above example reads the contents of a text file and prints it to the screen. Note that we used a new member function called EOF, which is Ifstream inherited from class iOS and returns True when the end of the file is reached.

Validation of status identifiers (verification of State flags)

In addition to EOF (), there are member functions that verify the state of the stream (all return bool type return values):

    • Bad ()

      Returns true if an error occurs during read and write. For example: When we want to write to a file that is not open as a write state, or if the device we are writing to has no space left.

    • Fail ()

      In addition to the same case as bad () returns True, plus a format error returns true, for example, 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 are called to return true.

To reset the status flags checked by the above member function, you can use the member function clear () without parameters.

Get and set the stream pointer (get and put stream pointers)

All input/output stream objects (I/O streams objects) have at least one flow pointer:

    • Ifstream, like IStream, has a pointer called get pointer, pointing to the next element that will be read.
    • Ofstream, similar to Ostream, has a pointer put pointer that points to the position where the next element is written.
    • FStream, similar to iostream, inherits both get and put

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

    • Tellg () and TELLP ()

      These two member functions do not pass in parameters and return a value of type Pos_type (according to the ansi-c++ Standard), which is an integer that 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 flow 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 flow pointer is changed to point to an absolute position from the beginning of the file calculation. The parameter type required to pass in is the same as the return value type of 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 start the calculation of a specific pointer determined by the parameter direction. It can be:

      Ios::beg Displacement calculated from the start of the stream
      Ios::cur Displacement calculated from the current position of the flow pointer
      Ios::end Displacement calculated at the end of the stream

The values of the stream pointer get and put are different for the calculation of the text file and the binary file, because some special characters in the text schema 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 value of Tellg or TELLP. For binary files, you can use these functions arbitrarily, and there should be no unexpected behavior generated.

The following example uses these functions to obtain the size of a binary file:

[CPP]View Plaincopyprint?
  1. Obtaining File Size
  2. #include <iostream.h>
  3. #include <fstream.h>
  4. Const char * filename = "Test.txt";
  5. int main () {
  6. long l,m;
  7. Ifstream in (filename, ios::in|ios::binary);
  8. L = In.tellg ();
  9. IN.SEEKG (0, Ios::end);
  10. m = In.tellg ();
  11. In.close ();
  12. cout << "size of" << filename;
  13. cout << "is" << (m-l) << "bytes.\n";
  14. return 0;
  15. }
  16. //Results:
  17. Size of Example.txt is bytes.



4. Binary files

In binary files, using << and >>, as well as functions such as getline, to enter and output data, have little practical meaning, although they are grammatically correct.

The file stream consists of two member functions that are specially designed for sequential read and write data: Write and read. The first function (write) is a member function of Ostream, which is inherited by Ofstream. Read is a member function of IStream, which is inherited by Ifstream. The objects of class fstream have both functions. Their prototypes are:

Write (char * buffer, streamsize size);
Read (char * buffer, streamsize size);

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

[CPP]View Plaincopyprint?
  1. Reading binary file
  2. #include <iostream>
  3. #include <fstream.h>
  4. Const char * filename = "Test.txt";
  5. int main () {
  6. char * buffer;
  7. long size;
  8. Ifstream in (filename, ios::in|ios::binary|ios::ate);
  9. Size = In.tellg ();
  10. IN.SEEKG (0, Ios::beg);
  11. Buffer = new char [size];
  12. In.read (buffer, size);
  13. In.close ();
  14. cout << "The complete file was in a buffer";
  15. delete[] buffer;
  16. return 0;
  17. }
  18. //Operation result:
  19. The complete file was 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 and physical files. For example, for an output stream, each time the member function put (write a single character) is called, the character is not directly written to the corresponding physical file of the output stream, but is first inserted into the stream's cache (buffer).

When the cache is discharged (flush), all of its data is either written to the physical medium (if it is an output stream), or simply erased (if it is an input stream). This process is called Synchronization (synchronization), and it occurs in any of the following situations:

      • When the file is closed: all caches that have not been completely 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 explicitly indicates that synchronization occurs when certain specific controls in the stream are encountered. These controls include: Flush and Endl.
      • explicit call to function Sync (): Call member function sync () (no parameters) can cause immediate synchronization. This function returns an int value equal to 1 to indicate that the stream has no contact with the cache or the operation failed.

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

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.