C ++ File Operations

Source: Internet
Author: User

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 opens the file for the input (read)
Ios: out opens a file for output (write)
Ios: ate initial location: End of the file
Ios: append all app outputs to the end of the file
Ios: trunc if the file already exists, delete the file first.
Ios: binary

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 );

All the member functions of ofstream, ifstream, and fstream of these classes open a file by default. The default methods of these three classes are different: the default method of class Parameters
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.

By
For Classes ofstream, ifstream, and fstream
The first operation of the object is usually to open the file. These classes have a constructor that can directly call open
Function with the same parameters. In this way, we can perform the same operations as the preceding definition object and open file: 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 <fstream>using namespace std;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;}

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

// reading a text file#include <iostream>#include <fstream>#include <cstdlib>using namespace std;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: The Shift calculated by cur from the current position of the stream pointer
Ios: end: the displacement calculated from the end of the stream.

Stream pointer get and put values for text files and binary files
File), because some special characters in a text file may be modified. For this reason, we recommend that you always use seekg and
The first seekp prototype, and do not apply to 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>#include <fstream>using namespace std;int main (){    const char * filename = "example.txt";    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.

Text
The component stream includes two member functions specially designed for sequential Data Reading and Writing: write and read. The first function (write) is ostream.
Is inherited by ofstream. Read is a member function of istream and is inherited by ifstream. Fstream
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>using namespace std;int main (){    const char * filename = "example.txt";    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 work with a streambuf
Buffer is associated. 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 member function put
(Write a single character) is called. This character is not directly written into the physical file corresponding to the output stream, but 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 a 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 restrictions. When the cache is full, it is automatically synchronized.
The control operator explicitly specifies that synchronization occurs when a specific control operator in the stream is encountered. These controllers include flush and endl.
Explicitly call the function sync (): 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.
In C ++, there is a stream class. All I/O is based on this "stream" class, including the file I/O we want to know, stream has two important operators:

1. Plug-in (<)
Output data to the stream. For example, the system has a default standard output stream (cout), which generally refers to the display. Therefore, cout <"Write Stdout" <'n '; output the string "Write Stdout" and line feed character ('n') to the standard output stream.

2. Analyze (>)
Input data from the stream. For example, the system has a default standard input stream (cin), which generally refers to the keyboard. Therefore, cin> x; read data of a specified type (that is, the type of variable x) from the standard input stream.

In C ++, operations on files are implemented through the fstream (file stream) subclass of stream. Therefore, to operate files in this way, you must add the header file fstream. h. The following describes how to operate such files.

1. Open a file
In the fstream class, a member function open () is used to open a file. Its prototype is:

Void open (const char * filename, int mode, int access );

Parameters:

Filename: name of the file to be opened
Mode: how to open the file
Access: Open File Attributes
The file opening method is defined in class ios (which is the base class of all stream I/O classes). The common values are as follows:

Ios: app: open a file in append Mode
Ios: ate: After the file is opened, it is located at the end of the file. ios: app contains this attribute.
Ios: binary: open a file in binary mode. The default mode is text. For the differences between the two methods, see the previous article.
Ios: in: open the file as input
Ios: out: open an output file
Ios: nocreate: The file is not created, so opening fails if the file does not exist.
Ios: noreplace: Does not overwrite the file. Therefore, if the file fails to be opened
Ios: trunc: if the file exists, set the file length to 0.
You can use "or" to connect the preceding attributes, for example, ios: out | ios: binary.

The attribute value for opening a file is:

0: normal file, open access
1: Read-Only files
2: Implicit File
4: system files
You can use "or" or "+" to connect the above attributes. For example, 3 or 1 | 2 means opening the file with read-only and implicit attributes.

For example, open the file c: config. sys in binary input mode.

fstream file1;file1.open("c:config.sys",ios::binary|ios::in,0);

If the open function only has one parameter for the file name, it is opened by reading/writing a common file, that is:

file1.open("c:config.sys");<=>file1.open("c:config.sys",ios::in|ios::out,0);

In addition, fstream has the same constructor as open (). For the above example, you can open the file at the time of definition:

fstream file1("c:config.sys");

In particular, fstream has two sub-classes: ifstream (input file stream) and ofstream (outpu file stream). ifstream opens the file as input by default, ofstream opens the file in output mode by default.

Ifstream file2 ("c: pdos. def"); // open the file ofstream file3 ("c: x.123") as input; // open the file as output

Therefore, in actual applications, select different classes as needed: If you want to open them as input, use ifstream to define them; if you want to open them as output, define it with ofstream. If you want to open it in input/output mode, define it with fstream.

Ii. Close files
You must close the opened file after it is used. fstream provides the member function close () to complete this operation, for example, file1.close (); to close the file connected to file1.

3. Read and Write files
Reading and writing a file can be divided into reading a text file and a binary file. reading a text file is relatively simple, and it can be done with an insertor or an analyzer. Binary reading is more complex, the two methods are described in detail below.

1. Read and Write text files
The reading and writing of text files is very simple: Use the plug-in (<) to output data to the file; Use the extract (>) to input data from the file. Suppose file1 is opened as input, and file2 is opened as output. Example:

File2 <"I Love You"; // write the string "I Love You" int I; file1> I; // enter an integer from the file.

This method also provides a simple formatting capability, such as specifying the output as hexadecimal. The specific formats include:

Operator Input/Output
Format dec as a decimal Value Data Input and Output
Endl outputs a line break and refresh the output.
Ends outputs an empty character output
Hex format to hexadecimal value data input and output
Oct format to octal numeric data input and output
Setpxecision (int p) is used to set the number of precise digits of a floating point.

For example, to output 123 as a hexadecimal value: file1

2. Binary file read/write
① Put ()
The put () function writes a character to the stream. Its prototype is ofstream & put (char ch), which is also relatively simple to use, such as file1.put ('C '); it is to write a character 'C' to the stream '.

② Get ()
The get () function is flexible and has three common overload methods:

One is the form corresponding to put (): ifstream & get (char & ch); the function is to read a character from the stream and save the result in the reference ch, if it is at the end of the file, null characters are returned. For example, file2.get (x); indicates reading a character from the file and saving the read character in x.

The prototype of another form of overload is: int get (); this form returns a character from the stream. If it reaches the end of the file, it returns EOF, for example, x = file2.get (); the function is the same as that of the previous example.

Also
One prototype is: ifstream & get (char * buf, int num, char
Delim = 'n'); in this form, the characters are read into the array directed by the buf until the num character is read or the character specified by delim is encountered.
The default line break 'N' will be used for the delim parameter '. For example:

File2.get (str1, 127, 'A'); // read the character from the file to str1. It is terminated when 'A' or 127 characters are read.

③ Read/write data blocks
To read and write binary data blocks, use the member functions read () and write (). Their prototype is as follows:

read(unsigned char *buf,int num);write(const unsigned char *buf,int num);

Read () reads num characters from the file to the cache pointed to by the buf. If the number of num characters has not been read at the end of the file, you can use the member function int gcount (); and write () writes num characters from the cache directed to the buf to the file. It is worth noting that the cache type is unsigned char *, sometimes type conversion is required.

Example:

Unsigned char str1 [] = "I Love You"; int n [5]; ifstream in ("xxx. xxx "); ofstream out (" yyy. yyy "); out. write (str1, strlen (str1); // write all str1 strings to yyy. in yyy. read (unsigned char *) n, sizeof (n); // from xxx. read the specified integer in xxx. Note that the type conversion is in. close (); out. close ();

Iv. EOF Detection
The member function eof () is used to check whether it has reached the end of the file. If it has reached the end of the file, a non-0 value is returned; otherwise, 0 is returned. The prototype is int eof ();

Example:

If (in. eof () ShowMessage ("it has reached the end of the file! ");

V. File locating
And
C file operations are different: C ++
The I/O system manages two pointers associated with one file. One is the read pointer, which indicates the position of the input operation in the file; the other is the write pointer, which is the position of the next write operation. Each time an input or output is executed,
The corresponding pointer automatically changes. Therefore, file location in C ++ is divided into read location and write location. The corresponding member functions are seekg () and
Seekp (), seekg () is to set the read location, seekp is to set the write location. Their most common forms are as follows:

istream &seekg(streamoff offset,seek_dir origin);ostream &seekp(streamoff offset,seek_dir origin);

Streamoff is defined in iostream. h, and defines the maximum value that can be obtained by offset. seek_dir indicates the reference position for moving and is an enumeration with the following values:

Ios: beg: Start of the file
Ios: cur: current file location
Ios: end of the file
These two functions are generally used in binary files, because text files may be different from the expected values due to the system's interpretation of characters.

Example:

File1.seekg (1234, ios: cur); // move the file's read pointer from the current position to the back of the 1234-byte file2.seekp (1234, ios: beg ); // shift the write pointer of the object from the beginning to the back of the object by 1234 bytes
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.