C ++ File Operations

Source: Internet
Author: User
Tags types of functions

Many people use the file type pointer file under ansi c in C ++ programming to execute file-related operations, which inevitably affects C ++ProgramOverall aesthetics. In addition, the C ++ standard Io Library provides a more complete and easy-to-use file operation method. Therefore, we recommend that you use the standard library to implement file input/output and cultivate a good programming habit.

1. File Input and Output

The header files for file operations include: ifstream provides the File Reading function; ofstream provides the file writing function; fstream provides the File Reading and Writing Function (including the first two types of functions, read/write operations on the same file ).
A. Define the object

 
Ifstream infile;//Define input objectOfstream OUTFILE;//Define output object

B. Before using fstream objects, you must bind these objects to the files to be read and written.

Infile. Open ("In.txt");//Enter the in.txt FileOUTFILE. Open ("Out.txt");//Output out.txt File

Of course, the fstream class provides constructor, which can implement the above two steps during initialization when defining objects.

Ifstream infile ("In.txt");//Define the infileobject and enter the content of the in.txt FileOfstream OUTFILE ("Out.txt");//Define the outfileobject and output the content to the out.txt File

C. Check whether the file is successfully opened.

 
If(!Infile) {cout<"Error: Unable to open the file"<Endl;Return-1;}

D. File Content Processing

I. 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.

 
//Input File, used for processingIf(!Infile. EOF () {process ();}

II. files can be divided into text files and binary files. The process of text files is relatively simple, and you can use the plug-in and analysis tool. The process of binary files is more complex, the following two methods are described respectively.

Text File: output to the file with the plug-in (<), and input from the file with the plug-in (>. Assume that infile is opened as input, and OUTFILE is opened as output.

 
OUTFILE <"Output to file";StringWord; infile> Word;//The file content is input to word, which is a string in the file

This method also provides a simple formatting capability, such as specifying the output as hexadecimal.

Operator Function Input/Output
Dec Formatted as a decimal Value Input and Output
HEX Formatted as a hexadecimal value Input and Output
Oct Formatted as octal numeric data Input and Output
Setpxecision (int p) Set the number of precise digits of a floating point. Output
Endl Output A linefeed and refresh the stream Output
Ends Output an empty character Output

For example, to output 123 as a HEX: OUTFILE
Getline function, one line of input file, function prototype

 
Istream & Getline (istream &Is,String& STR,CharDelim); istream& Getline (istream &Is,String& Str );

Read the string from is and store it in STR until the delimiter delim is encountered. For the second form, Getline encounters '\ n' stop. During execution, if delim appears, it will be read and discarded, and the next input will start after it.

Binary File: 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 OUTFILE. put ('C'); is to write a character 'C' to the stream '.

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, infile. Get (x); indicates to read a character from the file and save the character to 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.

Another prototype is ifstream & get (char * Buf, int num, char delim = ''). In this form, the characters are read into the array pointed by the Buf, the default value of the Line Break ''is used if the num character is read or the character specified by delim is encountered ''.

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

 
Read (unsignedChar* Buf,IntNum); write (ConstUnsignedChar* Buf,IntNum );

III. file Location. c ++ file location can be divided into read location and write location. The corresponding member functions are seekg () and seekp (). seekg () is used to set the read location, seekp is used to set the write position. Their most common forms are as follows:

Istream &Seekg (streamoff offset, seek_dir origin); ostream& Seekp (streamoff offset, seek_dir origin );

Offset defines the offset. seek_dir indicates the reference position for moving. It is an enumeration with the following values:

IOS: Beg: Start of the file

IOS: cur: current file location

IOS: end: End of the file

These two functions are generally used for binary files (bytes), because text files may be different from the expected values due to the system's interpretation of characters.

 
File1.seekg (1234, IOS: cur );//The read pointer of the file is removed 1234 bytes from the current position.File2.seekp (1234, IOS: Beg );//Transfers the write pointer of an object from the beginning to the back of the object by 1234 bytes.

E. close the file

When the program ends or the fstream object is associated with another file, the current file must be closed first.

 
Infile. Close ();//Disable infile

2. File Mode

When opening a file, you must specify the file mode whether to call open or use the file name as a part of stream initialization. Both the file stream constructor and open function provide default parameters to set the file mode. The default value varies depending on the stream type. The common file modes and meanings are as follows:

File Mode Description
In Open a file for read Operations
Out Open a file for write operations
App Find the end Of the file before each write
Ate Locate the file at the end of the file when opening the file
Trunc Clear an existing file stream when opening the file
Binary Perform Io operations in binary mode

A stream opened in binary mode processes the file in a byte sequence without interpreting the characters in the stream.

By default, the files associated with the ifstream stream are opened in mode and the files associated with the ofstream are opened in out mode. Files opened in out mode are cleared and all data stored in the file is discarded. In effect, the out mode specified for the ofstream object is equivalent to the out and trunc modes specified.

Mode Combination. Multiple File modes can be specified at the same time, but some combinations are meaningless. The common combination modes are as follows:

combination mode meaning
Out | app open the file and write it at the end of the file
Out | trunc open the file and perform the write operation to delete the existing data of the file (same as that of the out)
In | out open the file for read and write operations and locate it at the beginning of the file
In | Out | trunc open the file for read and write operations and delete existing data in the file
In | Out | ate open the file for read and write operations and locate it at the end of the file
...... ......
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.