A detailed description of C + + file operation (Ifstream, Ofstream, FStream)

Source: Internet
Author: User



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:


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 flags:

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 identifiers can be used in combination with the "or" operator (|) in the middle 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:

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, and the default way for these three classes is different:

Class

Default method for 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 thing as the above definition objects and open files in the following ways:

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.

Attention:

Ofstream is from memory to hard disk, Ifstream is from hard disk to memory, in fact, so-called stream buffer is memory space

ofstream is from the memory to the hard disk, Ifstream is from the hard disk to the memory, in fact the so-called stream buffer is the memory space;
in C + +, there is a stream 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, insert (<<)
to stream output data. 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, the disjunction (>>)
enters 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.

One, open file
in the FStream class, there is a member function open (), which is used to open the file, the prototype is:
Void open (const char* filename,int mode,int access); Parameters:
FileName:     file name to open
Mode: How to open the file
Access:   ; Open the properties of a file

The way the file is opened is defined in class iOS (the base class for all streaming I/O classes), and the commonly used values are as follows:
Ios::app: Open file in Append
Ios::ate: &N BSP; When the file is opened and positioned to the end of the file, Ios:app contains this property
Ios::binary:     Opens the file in binary mode, which is the default way of text. The difference between the two methods is shown in the preceding

       ios::in:   file opens as input ( File data input to memory)
Ios::out:   does not establish a file, so the file does not exist when open fails
Ios::noreplace: do not overwrite files , so if the file has failed when you open the file
Ios::trunc:   if the file exists, set the file length to 0
you can use "or" to connect the above attributes. Ios::out|ios::binary

Open File property value is:
0: Normal file, open access
1: Read-only file
2: Hidden file
4: System file

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);
Because 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 is different:

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"); Open in input/output mode
Ifstream file2 ("C:\\pdos.def"); Open File as input
Ofstream file3 ("c:\\x.123"); Open file in output mode

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
Like 123 as hex 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 pointed to by BUF until NUM characters are read or a character specified by Delim is encountered. If you do not use the Delim parameter, the default 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 from the cache pointed to by BUF to a file , 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. Therefore, C + + file positioning is divided into read position and write location, corresponding member functions are SEEKG () and SEEKP (). SEEKG () is the set read position, SEEKP is the 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 a file back 1234 bytes from the current position
FILE2.SEEKP (1234,ios::beg); Move the file's write pointer back 1234 bytes from the beginning of the file


A detailed description of C + + file operation (Ifstream, Ofstream, FStream)

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.