C + + file operations

Source: Internet
Author: User

C + + file Operations Summary:

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 (|) 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 to implement: Ofstream file;
File.Open ("Example.bin", Ios::out | ios::app | ios::binary);
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: the default way for class parameters
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 as above to define the object and open the file operation: 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. We use the overloaded insert operator <<, as shown in the following example:
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;
}
Reading data from a file can also be used in the same way as CIN:
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 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>
#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 bytes.
Binaries (binary files)
In binary files, using << and >&gt, 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>
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 was in a buffer";
delete[] buffer;
return 0;
}
The complete file was in a buffer
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.
In C + +, there is a stream in this class, all I/O is based on this "stream" class, including the files we want to know i/o,stream this class has two important operators:
1. Insertion device (<<)
Outputs data to the stream. For example, the system has a default standard output stream (cout), usually refers to the display, so,cout<< "write Stdout" << ' n '; means the string "write Stdout" and the newline character (' n ') Output to the standard output stream.
2. Extraction Device (>>)
Enter data from the stream. For example, the system has a default standard input stream (CIN), which is normally referred to as the keyboard, so,cin>>x; is the data that reads a specified type (that is, the type of the variable x) from the standard input stream.
In C + +, the operation of the file is implemented through the subclass FStream (file stream) of the stream, so to manipulate the file in this way, the header file fstream.h must be added. The following is the process of this type of file operation one by one.
First, open the file
In the FStream class, there is a member function open (), which is used to open the file, and its prototype is:
void Open (const char* filename,int mode,int access);
Parameters:
FileName: The file name to open
Mode: How to open a file
Access: Open the properties of a file
The way you open a file is defined in class iOS (the base class for all streaming I/O classes) and the values that are commonly used are as follows:
Ios::app: Open file in Append mode
Ios::ate: The file is opened and positioned to the end of the file, Ios:app contains this property
Ios::binary: Open the file in binary mode, the default way is text mode. The difference between the two methods is shown in the previous article
Ios::in: File opens in input mode
Ios::out: File opens in output mode
Ios::nocreate: Do not create file, so file does not exist when open failed
Ios::noreplace: Do not overwrite file, so if file exists failure when opening file
Ios::trunc: If the file exists, set the file length to 0
You can use "or" to connect the above attributes, such as Ios::out|ios::binary.
The properties of the open file are values:
0: Normal file, open access
1: Read-only files
2: Implied file
4: System files
You can use "or" or "+" to connect the above properties, such as 3 or 1|2 to open the file with read-only and implied properties.
Example: Opening a file as a binary input C:config.sys
FStream file1;
File1.open ("C:config.sys", ios::binary|ios::in,0);
If the open function has only one parameter for the file name, it is opened with a read/write normal file, namely:
File1.open ("C:config.sys"); <=>file1.open ("C:config.sys", ios::in|ios::out,0);
In addition, FStream also has the same constructor as open (), and for the above example, you can open the file when you define it:
FStream file1 ("C:config.sys");
In particular, FStream has two subclasses: ifstream (input file stream) and Ofstream (OUTPU file stream), and Ifstream opens the file as input by default. Ofstream, by default, opens the file in the output mode.
Ifstream file2 ("C:pdos.def");//Open file as input
Ofstream file3 ("c:x.123");//Open file in output mode
Therefore, in the actual application, according to the needs of different, choose different classes to define: If you want to open in the input mode, use Ifstream to define, if you want to open in the output, use Ofstream to define, if you want to open in the input/output mode, use FStream to define.
Second, close the file
Open files must be closed after use, FStream provides a member function close () to complete this operation, such as: File1.close (), the file1 connected file is closed.
Iii. Read and write files
Read and write files are divided into text files and binary files read, for the text file reading is relatively simple, with the insertion and the profiler can be, and for the binary reading is more complicated, the next to the detailed introduction of these two ways
1. Reading and writing of text files
Reading and writing text files is simple: Use the plug-in (<<) to output to the file, and use the Profiler (>>) to import from the file. Suppose the file1 is opened as input, File2 is opened with output. Examples are as follows:
file2<< "I love You";//write The string "I love You" to the file
int i;
file1>>i;//Enter an integer value from the file.
This way there is a simple format, such as the output can be specified as 16 and so on, the specific format has the following
operator function input/output
Dec formatted as decimal numeric data input and output
Endl outputs a newline character and refreshes the stream output.
Ends output a null character output
Hex formatted as hexadecimal numeric data input and output
Oct formatted as octal numeric data input and output
setpxecision (int p) Sets the precision bit output of a floating-point number
For example, to use 123 as the hexadecimal output:file1<2. Read and write binary files
①put ()
The put () function writes a character to the stream, and its prototype is Ofstream &put (char ch), which is simpler to use, such as File1.put (' C '), which is to write a character ' C ' to the stream.
②get ()
The Get () function is more flexible and has 3 commonly used overloaded forms:
One is the form that corresponds to the put (): Ifstream &get (char &ch), the function is to read a character from the stream, the result is saved in the reference CH, if the end of the file, the null character is returned. such as File2.get (x); indicates that a character is read from a file and the read word is characters in X.
Another overloaded form of the prototype is: int get (); This form returns a character from the stream, if it reaches the end of the file, it returns EOF, such as X=file2.get (), and the previous example function is the same.
Another form of prototyping is: Ifstream &get (char *buf,int num,char delim= ' n '), which reads characters into an array that is pointed to by BUF until NUM characters are read in or encounters a character specified by Delim if not used Delim This parameter, the default value newline character ' n ' will be used. For example:
File2.get (str1,127, ' a ');//reads a character from a file to a string str1, terminating when the character ' A ' is encountered or 127 characters are read.
③ read and write data blocks
To read and write binary data blocks, use the member function read () and the Write () member functions, which are prototyped as follows:
Read (unsigned char *buf,int num);
Write (const unsigned char *buf,int num);
Read () reads num characters from a file into the cache pointed to by buf, and if it is at the end of the file when NUM characters have not been read, you can use the member function int gcount () to get the number of characters actually read, while write () writes NUM characters to the file from the cache pointed to by BUF , it is important to note that the type of cache is unsigned char *, which may sometimes require a type conversion.
Cases:
unsigned char str1[]= "I love You";
int n[5];
Ifstream in ("xxx.xxx");
Ofstream out ("yyy.yyy");
Out.write (Str1,strlen (STR1));//write the string str1 all to Yyy.yyy
In.read ((unsigned char*) n,sizeof (n));//Read the specified integer from the xxx.xxx, note the type conversion
In.close (); Out.close ();
Iv. Detection of EOF
The member function EOF () is used to detect whether the end of the file is reached, or 0 if the end of the file returns a value other than 0. The prototype is an int eof ();
Cases:
if (in.eof ()) ShowMessage ("has reached the end of the file! ");
V. Positioning of documents
Unlike the C file operation, the C + + I/O system manages two pointers that are associated with a file. One is a read pointer, which shows the position of the input operation in the file, and the other is the position of the write pointer, which is the next write operation. Each time the input or output is executed, the corresponding pointer changes automatically. So, C + + file positioning is divided into read position and write location, corresponding member function is SEEKG () and SEEKP (), SEEKG () is set to read position, SEEKP is set write position. Their most common form is as follows:
IStream &AMP;SEEKG (Streamoff offset,seek_dir origin);
Ostream &AMP;SEEKP (Streamoff offset,seek_dir origin);
Streamoff, defined in iostream.h, defines the maximum value that offset offset can achieve, Seek_dir represents the base position of the move, and is an enumeration with the following values:
Ios::beg: File Start
Ios::cur: File Current Location
Ios::end: End of File
These two functions are typically used in binary files because the text file may be different from the expected value because the system interprets the characters.
Cases:
FILE1.SEEKG (1234,ios::cur);//Move the read pointer of the file backward from the current position by 1234 bytes
FILE2.SEEKP (1234,ios::beg);//Move the file's write pointer back 1234 bytes from the beginning of the file

C + + file operations

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.