A detailed description of C + + file operations

Source: Internet
Author: User

C + + supports the input and output of files through the following classes:

Ofstream: File class for write operation (output) (from Ostream)

Ifstream: Read operation (input) of the file class (from IStream extension)

FStream: A file class that can read and write operations concurrently (from iostream)

Opening a file (open a files)

The first thing you do with an object on one of these classes is usually to associate it with a real file, which means to open a file. An open file is represented by a stream object (Stream object) in the program (an instance of these classes), and any input-output operation on the stream object is actually the operation of the file.

To open a file through a Stream object, we use its member function open (): Void open (const char * filename, openmode mode);

Here filename is a string representing the name of the file to be opened, and mode is a combination of the following: 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 appended to the end of the file

Ios::trunc if the file already exists, delete the file first

Ios::binary binary mode

These identifiers can be used in combination with the "or" operator (|) in the middle Interval. For example, if we want to open the file "Example.bin" in binary mode to write some data, we can call the member function open () in the following way:

#include <fstream>usingnamespace  std; int Main () {Ofstream file;file.open ("example.bin", iOS:: Out | Ios::app | ios::binary); return 0 ;}

Ofstream, Ifstream and fstream all of these class member functions open contain a default way to open the file, the default way of the three classes is different: The default way of the class parameter

Ofstream Ios::out | Ios::trunc

Ifstream ios::in

FStream Ios::in | Ios::out

The default value is only used if the function is called without declaring the method argument. If any arguments are declared when the function is called, the default values are completely overwritten, not combined with the calling parameters.

Because the first operation on the objects of class Ofstream, Ifstream, and fstream are usually open files, these classes have a constructor that can call the open function directly and have the same parameters. In this way, we can do the same thing as the above definition objects and open files in the following ways:

Ofstream file ("example.bin", iOS:: Out | Ios::app | Ios::binary);

Both of these open files are the correct way.

You can check whether a file has been successfully opened by calling the member function Is_open (): bool Is_open ();

It returns a Boolean (bool) value that is true (true) to indicate that the file has been successfully opened, and False (false) is reversed.

Closing files (Closing a file)

When the file read and write operation is complete, we must close the file so that the file becomes accessible again. Closing a file requires calling the member function close (), which is responsible for draining the data from the cache and closing the file. Its format is simple: void close ();

Once this function is called, the original stream object can be used to open other files, and the file can be re-accessed by all other processes (process).

To prevent the flow object from being destroyed when the open file is also contacted, the destructor (destructor) automatically calls the Close function closed.

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. As shown in the following example, we use the overloaded insert operator <<://Writing on a text file

#include <fiostream.h>int  main () {Ofstream examplefile ("example.txt" ); if  "This wasa line.\n""This isanother line.\n " ; Examplefile.close ();} return 0 ;}

File Example.txt

This was a line.

This was another line.

Reading data from a file can also be used in the same way as CIN://reading a text file

#include <iostream.h>#include<fstream.h>#include<stdlib.h>intMain () {Charbuffer[ the];ifstream Examplefile ("Example.txt");if(!Examplefile.is_open ()) {cout<<"Error Opening file"; Exit (1); } while(!examplefile.eof ()) {examplefile.getline (buffer, -); cout<< Buffer <<Endl;}return 0;}

This was a line.

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 The displacement calculated from the beginning of the stream

Ios::cur the displacement calculated from the current position of the flow pointer

Ios::end the 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://Obtaining File size

#include <iostream.h>#include<fstream.h>Const Char* filename ="Example.txt";intMain () {Longl,m;ifstream file (filename, iOS::inch|ios::binary); l=File.tellg (); FILE.SEEKG (0, ios::end); M=File.tellg (); File.close (); cout<<"size of"<<Filename;cout<<" is"<< (m-l) <<"bytes.\n";return 0;}

Size of Example.txt is bytes.

Binaries (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). Reading binary file

#include <iostream>#include<fstream.h>Const Char* filename ="Example.txt";intMain () {Char*buffer;Longsize;ifstream file (filename, iOS::inch|ios::binary|ios::ate); Size=File.tellg (); FILE.SEEKG (0, Ios::beg); buffer=New Char[Size];file.read (buffer, size); File.close (); cout<<"The complete file was in a buffer";Delete[] buffer;return 0;} the complete file is inchA buffer

A detailed description of C + + file operations

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.