Ofstream ifstream File Operations

Source: Internet
Author: User

The category Declaration of the output and input guide screen and keyboard in c ++ contains the title file <iostrream. h>, while the I/O of a disk file declares that it contains the title file <fstream. h>.
Input and Output formats:
Output to disk ofsteam recognition ("file name ")
Read an ifsteam file from a disk ("file name")
For example:
Ofstream outfile ("data.txt"); // write it to your data.txt file.
Format input and output:
1. Input and Output of Integer Data
The integer data is stored in the disk, and each text occupies one byte.

For example:
# Include <fstream. h>
# Include <iostream. h>
# Inlude <conio. h>
Void main ()
{
Ofstream outfile ("data.txt"); // write the file
For (int I = 0; I <10; I ++)
Outfile <I <""; // space is used to avoid the addition of numerical values. The file size is 20 bytes.
Cout <"OK, press a key! ";
Gerch ();
}

After the program is executed, open it in notepad to view the data.
0 1 2 3 4 5 6 7 8 9
The statement for reading files is:
Int data;
Ifstream infile ("data.txt ");
For (INT I = 0; I <10; I ++)
{
Infile> data; // The data can be fully read only when there is a space between the data,
Cout <data <"; // output to the screen, with spaces to separate numbers
}

2-character data input
The output mode of characters is put (CH) as the statement for saving, and the read Statement is get (Ch)
For example:
Char STR [] = "Hello this is a C ++ programe! /N"
"I know this difference/N"
"And mocive ";
Ofstream OUTFILE ("data.txt ");
For (INT I = 0; I <strlen (STR); I ++)
OUTFILE. Put (STR [I]);
 
Read:
Char ch;
Ifstream infile ("data.txt ");
While (infile)
{
Infile. get (ch );
Cout <ch;
}
Getch ();

3. String data input
When there is a large amount of data, the read/write speed is faster. When the input is complete, the entire line of string is added with a line break symbol. When reading data, use the getline (buffer, max) statement to read the entire row of data. When a line break occurs, the/n at the end of each line is not read, so a line break symbol must be added to the output, otherwise, the data will be connected together.
Example:
Ofstream outfile ("strdata.txt ");
Outfile <"use your vote/n ";
Outfile <"ouse your weise/n ";

Read:
Const MAX = 80;
Char buffer [MAX];
Ifstream infile ("strdata.txt ");
While (infile)
{
Infile. getline (buffer, MAX );
Cout <buffer <endl;
}

4 floating point number
Because floating point numbers have decimal points, they are the same as integers when storing data. As long as each data is added with a space, adjacent data can be separated.

6. binary files
The preceding formatting file occupies hard disk controls and uses binary storage to save a lot of controls. It uses write and read () to store and read data.
Ofstream ("file name", ios: binary );
Write (write address, write size)
Ifstream recognition words ("file name", ios: binary );
Recognized word. read (read address, read size );
For example, infile. read (char *) buffer, sizeof (data type ));
Close file
Recognized word. close ();
Example:
Ofstream outfile ("data. dat", ios: binary );
For (int I = 0; I <100; I ++)
{
N [0] = I + 1;
Outfile. write (Char *) n, sizeof (int); // you can also use variables and arrays as an example.
// Outfile. write (Char *) & I, sizeof (int); I is the variable
// Outfile. write (Char *) n, sizeof (int); n is an array
}
Outfile. close ();
Ifstream inifile ("data. dat", ios: binary );
For (I = 0; I <100; I ++)
{
Inifile. read (Char *) n, sizeof (int );
Cout <n [0] <"";
}

7. Random File Access
The file can be read at will. After reading the file, it can be updated. After the file is updated, it can be stored in the source file. Fstream file;

File. open ("file name", access mode );
File. open ("x. dat", ios: app | ios: in | ios: out | ios: binary );
In open file input or read ifstream
Open file output or write ofstream
Ate writes or reads data from the end of the file.
Append an app to the end of a file
If the arunc file exists, set its length to 0.
Open a binary file
The binary file has a pointer pointing to the position of the current data in the file. The pointer in this file is different from the pointer variable in general. It is just a pure indicator.

Function Introduction
Seekg ()
Seekg (0) pointer move to the beginning of the file
Seekg (0, ios: cur); treats the current pointer as 0
Seekg (0, ios: end); move the pointer to the end of the file. If file. tellg () is used together, you can find the size of the file in bytes.

The following two operations can be used only after the file is closed:
Remove ("file name"); Delete this file
Rename ("old file name", "new file name ");

# Include <iostream>
# Include <fstream>
Using namespace std;

Int main ()
{
Int n [5] = {1, 2, 3, 4, 5 };
Register int I;
 
Ofstream out ("test", ios: out | ios: binary );
If (! Out ){
Cout <"Cannot open file./n ";
Return 1;
}

Out. write (char *) & n, sizeof n );
Out. close ();
 
For (I = 0; I <5; I ++) // clear array
N [I] = 0;
 
Ifstream in ("test", ios: in | ios: binary );
If (! In ){
Cout <"Cannot open file./n ";
Return 1;
}
 
In. read (char *) & n, sizeof n );
For (I = 0; I <5; I ++) // show values read from file
Cout <n [I] <"";
 
In. close ();
Return 0;
}

 

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. Therefore, 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. The following describes how to operate such files.

1. Open a file
In the fstream class, a member function open () is used to open a file. Its prototype is:

Void open (const char * filename, int mode, int access );

Parameters:

Filename: name of the file to be opened
Mode: how to open the file
Access: Open File Attributes
The file opening method is defined in class ios (which is the base class of all stream I/O classes). The common values are as follows:

Ios: app: open a file in append Mode
Ios: ate: After the file is opened, it is located at the end of the file. ios: app contains this attribute.
Ios: binary: open a file in binary mode. The default mode is text. For the differences between the two methods, see the previous article.
Ios: in: open the file as input
Ios: out: open an output file
Ios: nocreate: The file is not created, so opening fails if the file does not exist.
Ios: noreplace: Does not overwrite the file. Therefore, if the file fails to be opened
Ios: trunc: if the file exists, set the file length to 0.
You can use "or" to connect the preceding attributes, for example, ios: out | ios: binary.

The attribute 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, 3 or 1 | 2 means opening the file with read-only and implicit attributes.

For example, open the file c: config. sys in binary input mode.

Fstream file1;
File1.open ("c: config. sys", ios: binary | ios: in, 0 );

If the open function only has one parameter for the file name, it is opened by reading/writing a common file, that is:

File1.open ("c: config. sys"); <=> file1.open ("c: config. sys", ios: in | ios: out, 0 );

In addition, fstream has the same constructor as open (). For the above example, you can open the file at the time of definition:

Fstream file1 ("c: config. sys ");

In particular, fstream has two sub-classes: ifstream (input file stream) and ofstream (outpu file stream). ifstream opens the file as input by default, ofstream opens the file in output mode by default.

Ifstream file2 ("c: pdos. def"); // open the file as input
Ofstream file3 ("c: x.123"); // open the file in output mode

Therefore, in actual applications, select different classes as needed: If you want to open them as input, use ifstream to define them; if you want to open them as output, define it with ofstream. If you want to open it in input/output mode, define it with fstream.

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 (); to close 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 two methods are described in detail below.

1. Read and Write text files
The reading and writing of text files is very simple: Use the plug-in (<) to output data to the file; Use the extract (>) to input 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" to the file"
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

2. Binary file read/write
① 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 '.

② 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, null characters are 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 (); 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 = 'n'). In this form, the characters are read into the array pointed by the buf, the default value of the Line Break 'n' is used if the num character is read or the character specified by delim is encountered '. 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.

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

Unsigned 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 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. The prototype is int eof ();

For example, if (in. eof () ShowMessage ("has reached the end of the file! ");

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 indicates the position of the input operation in the file; the other is the write pointer, which is the position of the next write operation. The corresponding pointer automatically changes each time the input or output is executed. Therefore, file location in C ++ 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 );

Streamoff is defined in iostream. h, and defines the maximum value that can be obtained by 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 of the file
These 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.

 

There are a lot more...

From

Http://www.cppblog.com/niewenlong/archive/2007/06/14/26302.html

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.