Input and Output of files in C ++

Source: Internet
Author: User
Document directory
  • Open a file)
  • Close a file)
  • Text mode files)
  • Verification of state flags)
  • Get and put stream pointers)
  • Binary files)
  • Cache and synchronization (buffers and synchronization)

C ++ supports file input and output through the following classes:

  • Ofstream: File class for write operations (output) (extended by ostream)
  • Ifstream: File class for read Operations (input) (extended by istream)
  • Fstream: A file class that supports simultaneous read/write operations (extended by iostream)

 

Open a file)

The first operation on an object of these classes is usually to associate it with a real file, that is, to open a file. The opened file is represented by a stream object in the Program (an instance of these classes ), any input/output operations on this stream object are actually operations on this 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 that represents the name of the file to be opened. mode is a combination of the following flags:

IOS: In Open a file for input (read)
IOS: Out Open a file for output (write)
IOS: ATE Initial Location: End of the file
IOS: app All outputs are appended at the end of the file.
IOS: trunc If the file already exists, delete the file first.
IOS: Binary Binary Mode

These identifiers can be combined and separated by the "or" Operator (|. 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 ways:

ofstream file;
file.open ("example.bin", ios::out | ios::app | ios::binary);
The member functions of ofstream, ifstream, and fstream of all these classes open a file by default. The default methods of these three classes are different:

Class Parameter default mode
Ofstream IOS: Out | IOs: trunc
Ifstream IOS: In
Fstream IOS: In | IOs: Out

The default value is used only when the function is called and the method parameter is not declared. If any parameter is declared when a function is called, the default value is completely rewritten without combining with the called parameter.

Because the first operation on objects of the ofstream, ifstream, and fstream classes is usually to open files, these classes have a constructor that can directly call open functions and have the same parameters. In this way, we can perform the same operations as defining objects and opening files as above:

ofstream file ("example.bin", ios::out | ios::app | ios::binary);Both methods are correct.

You can call the member function is_open () to check whether a file has been successfully opened:

bool is_open();It returns a Boolean value. True indicates that the file has been successfully opened, and false indicates that the opposite is true.

Close a file)

After the file read/write operation is complete, we must close the file to make it accessible again. To close a file, you need to call the member function close (), which is responsible for discharging the data in the cache and closing the file. The 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 accessed again by other processes.

To prevent the stream object from being destroyed by an opened file, the Destructor automatically calls the close function.

Text mode files)

Classes ofstream, ifstream, and fstream are derived from ostream, istream, and iostream respectively. This is why the fstream object can use its parent class to access data.

In general, we will use these classes to interact with the same member functions (CIN and cout) on the console for 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 (examplefile. is_open ()){
Examplefile <"This is a line./N ";
Examplefile <"this is another line./N ";
Examplefile. Close ();
}
Return 0;
}
File example.txt
This is a line.
This is another line.

You can use the same method as CIN to read data from a file:

// Reading a text file
# Include <iostream. h>
# Include <fstream. h>
# Include <stdlib. h> int main (){
Char buffer [256];
Ifstream examplefile (”example.txt ");
If (! Examplefile. is_open ())
{Cout <"error opening file"; exit (1 );}
While (! Examplefile. EOF ()){
Examplefile. Getline (buffer, 100 );
Cout <buffer <Endl;
}
Return 0;
}
This is a line.
This is another line.

The preceding example reads the content of a text file and prints it to the screen. Note that we use a new member function called EOF, which is inherited by ifstream from the IOS class and returns true when it reaches the end of the file.

Verification of state flags)

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

  • Bad ()Returns true if an error occurs during reading or writing. For example, if you want to write data to a file that is not in the write state, or the device that you want to write data to has no space left.
  • Fail ()In addition to bad (), true is returned. If a format error is added, true is returned. For example, if you want to read an integer and get a letter.
  • EOF ()Returns true if the read object reaches the end of the object.
  • Good ()This is the most common function: If you call any of the above functions to return true, this function returns false.

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

Get and put stream pointers)

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

  • Ifstream, similar to istream, has a pointer called get pointer pointing to the next element to be read.
  • Ofstream, similar to ostream, has a pointer put pointer pointing to the location where the next element is written.
  • Fstream, similar to iostream, inherits both get and put

We can use the following member functions to read or configure these stream pointers pointing to the read/write position in the stream:

  • Tellg () and tellp ()The two member functions do not need to pass in the parameter, return the value of the pos_type (according to the ANSI-C ++ standard), is an integer, representing the current get stream pointer position (with tellg) or the position of the put stream pointer (tellp ).
  • Seekg () and seekp ()These functions are used to change the stream pointer get and put positions respectively. Both functions are overloaded as two different prototypes:

    Seekg (pos_type position );
    Seekp (pos_type position );

    With this prototype, the stream pointer is changed to an absolute position starting from the file. The input parameter type must be the same as the return value type of the functions tellg and tellp.

    Seekg (off_type offset, seekdir direction );
    Seekp (off_type offset, seekdir direction );

    This prototype can be used to specify a displacement (offset) calculated starting from a specific pointer determined by the Direction parameter ). It can be:

    IOS: Beg Displacement calculated from the starting position of the stream
    IOS: cur Displacement calculated from the current position of the stream pointer
    IOS: End Displacement calculated from the end of the stream

Stream pointer get and put values have different calculation methods for text files and binary files, because some special characters in a text file may be modified. For this reason, we recommend that you always use the first prototype of seekg and seekp for files opened in text file mode, and do not modify the return values of tellg or tellp. For binary files, you can use these functions without any unexpected behavior.

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 = optional example.txt "; int main (){
Long l, m;
Ifstream file (filename, IOS: In | 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 40 bytes.
Binary files)

In binary files, using <and> and functions (such as Getline) to operator input and output data has no practical significance, although they conform to the syntax.

The file stream includes two member functions specially designed for sequential Data Reading and Writing: write and read. The first function (write) is a member function of ostream and is inherited by ofstream. Read is a member function of istream and is inherited by ifstream. Fstream-like objects have both functions. Their prototype is:

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

Buffer is a memory address used to store or read data. The size parameter is an integer that represents the number of characters to be read or written from the cache (buffer.

// Reading binary file
# Include <iostream>
# Include <fstream. h> const char * filename = optional example.txt "; int main (){
Char * buffer;
Long size;
Ifstream file (filename, IOS: In | 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 is in a buffer"; Delete [] buffer;
Return 0;
}
The complete file
Is in a buffer
Cache and synchronization (buffers and synchronization)

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

When the cache is flush, all the data in the cache or is written to the physical media (if it is an output stream ), or simply get erased (if it is an input stream ). This process is called synchronization and will occur in any of the following situations:

  • When the file is closed:Before the file is closed, all caches that have not been fully written or read will be synchronized.
  • When the cache buffer is full:Cache buffers has certain space limitations. When the cache is full, it is automatically synchronized.
  • The Controller explicitly states:Synchronization occurs when a specific Controller in a stream is encountered. These controllers include flush and Endl.
  • Call the function sync () explicitly ():Calling the member function sync () (without parameters) can cause immediate synchronization. This function returns an int value, which is equal to-1, indicating that the stream is not linked to the cache or the operation fails.
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.