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:
#include <fstream> ofstream // file Write memory write to storage device ifstream // File read operation, storage device read-in to in -memory fstream // read-write operation, read and write operation to open file
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 ()
Public member function void Const Char * filename, = 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);
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:
out ; Out. Open ("Hello.txt", iOS::in |ios::out |ios::binary ) // make the 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:
out ("... ", iOS::out); inch ("... ", iOS::in); FStream foi (" ... ", iOS::in |ios::out);
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:
//writing on a text file#include <fiostream.h>intMain () {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 isa line. this isAnother 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]; Ifstreaminch("Test.txt"); if(!inch. Is_open ()) {cout<<"Error Opening file"; Exit (1); } while(!inch. EOF ()) { inch. getline (Buffer, -); cout<< Buffer <<Endl; } return 0; } //results are output on the screenThis isa line. this isAnother 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:
//Obtaining File Size#include <iostream.h>#include<fstream.h>Const Char* filename ="Test.txt"; intMain () {Longl,m; Ifstreaminch(FileName, iOS::inch|ios::binary); L=inch. TELLG (); inch. SEEKG (0, Ios::end); M=inch. TELLG (); inch. Close (); cout<<"size of"<<filename; cout<<" is"<< (m-l) <<"bytes.\n"; return 0; } //Results: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).
//reading binary file#include <iostream>#include<fstream.h>Const Char* filename ="Test.txt"; intMain () {Char*buffer; Longsize; Ifstreaminch(FileName, iOS::inch|ios::binary|ios::ate); Size=inch. TELLG (); inch. SEEKG (0, Ios::beg); Buffer=New Char[size]; inch. Read (buffer, size); inch. Close (); cout<<"The complete file was in a buffer"; Delete[] buffer; return 0; } //Operation Result:The complete file is inchA 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.
Description: The above content is reproduced from Csdn blog (http://blog.csdn.net/kingstar158/article/details/6859379), personal feeling is very useful to themselves, so they all copied over, see the original please go (http:/ /blog.csdn.net/kingstar158/article/details/6859379).
C + + file read and write detailed (Ofstream,ifstream,fstream)