C++ ofstream and ifstream detailed usage

  • 2020-04-02 01:08:55
  • OfStack

In C++, there is a stream class, and all I/O is based on this "stream" class, including the files we want to know about I/O. The stream class has two important operators:

1. Inserter ( < < )

Output data to the stream. For example, the system has a default standard output stream (cout) < < "Write Stdout." " < < '\ n'; To output the string "Write Stdout" and the newline character ('\n') to the standard output stream.

2. Dissector ( > > )

Input data from the stream. For example, the system has a default standard input stream (cin), which is generally referred to as the keyboard, so cin > > X; Represents reading data of a specified type (that is, the type of the variable x) from the standard input stream.

In C++, the operation of a file is done through the subclass fstream(file stream) of stream, so to manipulate the file in this way, you must add the header file fstream.h. The following is a file of this kind of operation process.

Open the 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: the name of the file to open

Mode: how to open a file

Access: opens the file's properties

The way to open the file is defined in the ios class (which is the base class for all streaming I/O classes). The commonly used values are as follows:

Ios ::app: open the file as an append

Ios ::ate: file opened to locate the end of the file, ios:app contains this property

Ios ::binary: opens a file as a binary. The default is text. The difference between the two approaches is described above

Ios ::in: file opened as input (file data entered into memory)

Ios ::out: file open as output (memory data output to file)

Ios ::nocreate: does not create a file, so it fails to open if the file does not exist

Ios ::noreplace: does not overwrite the file, so open the file if the file exists failed

Trunc: if the file exists, set the file length to 0

You can connect the above attributes with "or", such as ios::out|ios::binary

The property value of the open file is:

0: normal file, open access

1: read only files

2: hidden files

4: system files

You can connect the above attributes with "or" or "+", such as 3 or 1|, 2 is to open the file with read-only and implicit attributes.

For example, open file c:\config.sys with binary input

Fstream file1.

File1. Open (" c: \ \ config sys ", the ios: : binary | ios: : in, 0).

If the open function takes only the filename as an argument, it opens as a read/write normal file, i.e. :

File1. Open (" c: \ \ config sys "); < = > File1. Open (" c: \ \ config sys ", the ios: : | in ios: : out, 0).

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

Fstream file1 (" c: \ \ config sys "); In particular, fstream has two subclasses: ifstream(input file stream) and ofstream(outpu file stream). Ifstream opens the file as input by default, while ofstream opens the file as output by default.

Ifstream file2 (" c: \ \ pdos. Def "); // open the file as input

Ofstream file3 (" c: \ \ x. 123 "); // open the file as output so, in practice, choose different classes to define according to your needs: if you want to open the file as input, use ifstream to define; If you want to open it as output, you define it as ofstream; If you want to open it as input/output, define it as fstream.

Close the file

Fstream provides the member function close() to do this, such as: file1.close(); Close the file connected to file1.

Read and write files

Read and write files are divided into text files and binary files read, for the text file read is relatively simple, with the inserter and disconnector can be; Binary reading is a bit more complicated, and we'll cover both in more detail

1. Read and write text files

Reading and writing text files is simple: use the inserter ( < < ) output to the file; With the dissector ( > > ) from a file. Suppose file1 is opened as input and file2 as output. Here's an example:

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 approach also has a simple formatting capability, such as the ability to specify hexadecimal output, and so on, in the following formats

Operator function input/output

Dec is formatted as decimal numeric data input and output

Endl prints a newline character and refreshes the stream output

Ends outputs a blank character

Hex is formatted as hex numeric data input and output

Oct is formatted as octal numeric data input and output

Setpxecision (int p) sets the precision number output of a floating point number

For example, to 123 as hexadecimal output: file1 <

2. Read and write binary files

1) put ()

The put() function writes a character to the stream. The prototype is ofstream &put(char ch). It's just writing a character 'c' to the stream.

(2) the get ()

The get() function is flexible and has three common overloads:

One is the corresponding form to put() : ifstream &get(char &ch); The function is to read a character from the stream, save the result in the reference ch, and return a null character if you go to the end of the file. Such as file2. Get (x); Means to read a character from a file and save the read character in x.

Another type of overloaded stereotype is: int get(); This form returns a character from the stream, and EOF if it reaches the end of the file, such as x=file2.get(); The function is the same as the above example.

Another form of the prototype is: ifstream &get(char *buf,int num,char delim='\n'); This form reads the character into the array pointed to by buf until the num character is read in or the character specified by delim is encountered. If delim is not used, the default newline '\n' is used. Such as:

File2. Get (str1, 127, 'A'); // reads characters from the file to the string str1 and terminates when the character 'A' is encountered or 127 characters are read.

Read and write data blocks

To read and write binary blocks, use the member functions read() and write(), which are prototyped as follows:

Read (unsigned char * buf, int num);

Write (const unsigned char *buf,int num);

Read () reads the num character from the file into the cache pointed by buf, and if the end of the file is reached before the num character is read, the member function int gcount() can be used. To get the number of characters actually read; While write() writes num characters from the cache pointed by buf to the file, it is worth noting that the type of cache is unsigned char *, and sometimes a type conversion may be required.

Ex. :

Unsigned char str1[]="I Love You";

Int n [5];

Ifstream in (" XXX, XXX ");

Ofstream out (" yyy. Yyy ");

Out. Write (str1, strlen (str1)); // write the entire string str1 to yyy.yyy

In the read ((unsigned char *) n, sizeof (n)); // read the specified integer from xxx. XXX, pay attention to the type conversion

In the close (); Out. The close (); Iv. Test EOF

The member function eof() is used to detect if the end of the file is reached, and returns a non-zero value if it is reached, or 0 if it is not. The prototype is int eof();

Example: if(in.eof())) ShowMessage(" has reached the end of the file!" );

Five, document location

Unlike in C, 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 location of the next write operation. Each time an input or output is executed, the corresponding pointer automatically changes. Therefore, C++ file location is divided into read location and write location location, the corresponding member functions are seekg() and seekp(). Seekg () sets the read location, and seekp sets the write location. Their most common form is as follows:

Cost & 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 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: file end

These two functions are typically used in binary files, because text files can differ from expected values depending on how the system interprets the characters. Ex. :

File1. Seekg (1234, the ios: : cur); // moves the file's read pointer back 1234 bytes from its current position

File2. Seekp (1234, the ios: : beg); // moves the write pointer back 1234 bytes from the beginning of the file

Related articles: