Reference: http://www.cppblog.com/lmlf001/archive/2006/04/18/5815.html (found some of them have problems ...)
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, so 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.
# Include <fstream. h>
3> fstream has two subclasses: ifstream (input file stream) and ofstream (outpu file stream)
Where,
Ifstream opens a file in Read mode by default.
Ofstream opens the file as input by default.
This can be seen from the constructor:
Ifstream (const char *Szname, IntNmode= IOs: In, int
Nprot= Filebuf: openprot );
IOS: In refers to reading from the file to the memory.
Ifstream objects can be read (), but not write;
Ofstream (const char * Szname, Int
Nmode = IOs: Out, int Nprot = Filebuf: openprot );
IOS: Out refers to reading data from the memory to the file.
The ofstream class object can perform write () operations, but not read () operations;
In actual applications, select different classes as needed: If you want to enable the class in Read mode, use ifstream to define it. If you want to enable the class in write mode, it is defined by ofstream;
If you want to enable it in read/write mode, fstream is used for definition.
1. Open a file
Use the member function open ()
Function prototype:
Void open (const char * filename, int mode, int access );
Parameters:
1> filename: name of the file to be opened
2> mode: how to open the file
The Mode for opening a file is defined in the class IOs (the base class of all stream I/O classes). The common values are as follows:
IOS: APP: open the file in append mode (garbled characters may occur ...)
IOS: ate: After the file is opened, it is located at the end of the file. IOS: app contains this attribute. (After the file is opened by default, both the read pointer and write pointer are located at the initial position of the file)
IOS: Binary: open a file in binary mode. The default mode is text.
IOS: In: open a file in Read mode (that is, you can perform read operations on the file in refers to the file from somewhere else to the memory)
IOS: Out: open the file in writing mode (that is, you can write the file out to the place from memory)
IOS: nocreate: The file is not created, so opening fails when the file does not exist (if the file does not exist by default, it will always be created automatically)
IOS: noreplace: The file is not overwritten. Therefore, if the file fails to be opened (subsequent read and write operations will fail)
Note: there will be no prompts after the failure (this is very tangled)
IOS: trunc: if the file exists, set the file length to 0 (the original file content will be cleared );
You can use "or" to connect the preceding attributes, for example, IOS: Out | IOs: binary.
3> access: attributes of the opened file
The attribute access 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, 1 + 2 or 1 | 2 is to open the file with read-only and implicit attributes.
For example, open the file c: \ config. sys in binary input mode.
fstream file; file.open("c:\\config.sys",ios::binary|ios::in,0);
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 (); closes 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 following describes the two methods in detail:
1. Read and Write text files
There are two methods to read and write text files:
Method 1: Use the plug-in (<) to write data to the file, and use the analytic volume (>) to read 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 <123; to output 3.1415926 with a 5-bit precision: file1 <3.1415926.
Question:
char data[32]={0};file>>data;
When ">" is used, only the first character in the file is read to data (when read () is used, the content can be fully read, probably because read () specifies the number of bytes to read)
Method 2: Use the fstream member function: Read ()/write ()
Read () indicates reading content from the file to destbuf;
The function prototypes are as follows:
Void read (char * destbuf, int readsize );
Write () indicates writing the content in srcbuf to the file;
The function prototype is as follows:
Void write (const char * srcbuf, int writesize );
I personally feel that method 2 is better, and binary files can be read and written, with better flexibility.
2. Binary file read/write
1> 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 '.
2> 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, an empty character is 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 ();
In this form, a character is returned from the stream. If it reaches the end of the file, eof, for example, x = file2.get (); is the same as that of the preceding example.
Another 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. If the delim parameter is not used, the default line break '\ n' will be used '. 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.
3> 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:
Nsigned 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. yyy.
In. Read (unsigned char *) n, sizeof (n); // read the specified integer from XXX. XXX. Pay attention to type conversion.
In. Close (); Out. Close ();
Iv. EOF Detection
The member function EOF () is used to check whether the object has reached the end of the file.
Function prototype:
Int EOF ();
Return Value:
If a non-0 value is returned at the end of the file, otherwise 0 is returned.
V. File locating
Unlike C's file operations, the C ++ I/O system manages two pointers associated with a file:
One is the read pointer, which records the position of the input operation in the file;
The other is the write pointer, which records the location of the next write operation.
The corresponding pointer automatically changes each time the input or output is executed.
Therefore, the corresponding member functions seekg (seek get) and seekp (seek put) are used to locate the positions of Read and Write pointers.
Specifically, seekg () sets the read position and seekp sets the write position. 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 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: End of the file
The 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 read pointer of the file from the current position to the back of the 1234 bytes
File2.seekp (1234, IOS: Beg); // transfers the write pointer of the object from the beginning to the back of the object by 1234 bytes.