File IO operation stream in C ++

Source: Internet
Author: User

The first two sections introduce the C ++ IO stream class library, member functions of some predefined stream objects in the standard device IO operation stream, and IO format control. Today, I will continue to introduce the stream operation content in C ++-file IO operation stream fstream. It will focus on how C ++ operates files.
A file is a collection of data stored on external media. We all know that the operating system manages data in units of files. Therefore, if you want to find the data of the external media, you must first find the specified file by file name, and then read the data from the file. If you want to save the data to the external media, if the file does not exist, you need to create a file and then input data to it. Due to the ever-changing file content and different sizes, file streams are processed in the form of file streams in C ++ for unified processing. File streams are data streams of input and output objects from external files. The output file stream indicates the data from the memory to the external storage file, while the input file stream is opposite. Based on the data organization in the file, the file can be divided into two types: text files and binary files. A text file is also called an ASCII file. Each byte of it stores an ASCII code, representing a character. Binary files store data in the memory in the disk as they are stored in the memory. For example, an integer of 20000 is in two bytes in the memory, and the output in text format occupies five bytes. Therefore, when output in text form, one byte corresponds to one character, which facilitates character output. The disadvantage is that it occupies a large amount of storage space. Data is output in binary format, which saves the conversion time and storage space, but cannot be output directly in the form of characters.
1. operations on files in C ++ are divided into the following steps: (1) create a file stream object; (2) open or create a file; (3) perform read/write operations; (4) close the file. The stream classes used for file IO operations mainly include three fstreams (input and output file streams), ifstream (input file streams), and ofstream (output file streams ); these three classes are included in the header file fstream. Therefore, operations on files in the program must contain the header file. First, create a stream object, and then use the file stream class member function open to open the file, that is, to associate the file stream object with the specified disk file. The open member function is generally in the following format:
File Stream object. open (file name, usage );
The file name can include a path (for example, e: \ c ++ \ file.txt). If the path is missing, the current directory is used by default. The usage is how the file is opened. Here are some usage methods of files, all of which are enumeration values in the ios base class:


 
In addition, note the following:
(1) Because nocreate and noreplace are closely related to the system platform, they are removed from the C ++ standard.
(2) Each opened file has a file pointer. the starting position of the pointer is specified by the open method. Each read/write operation starts from the current position of the file pointer. The pointer moves one byte after each read. When the file pointer is moved to the end, the file Terminator EOF is encountered. At this time, the value of the member function eof the stream object is not 0, indicating the end of the file.
(3) opening a file in mode can only be used to input data, and the file must already exist.
(4) open the file using the app method. The file must exist at this time. When the file is opened, the pointer is at the end, and this method can only be used for output.
(5) Use ate to open an existing file. The file pointer is automatically moved to the end of the file, and data can be written to it.
If the file needs to be opened in two or more ways, use "|" to separate and combine the files. In addition to opening a file using the open member function, you can also use the file stream class constructor to open the file. Its Parameters and default values are exactly the same as those of the open function. For example, stream is a file stream class (file name, usage method). If the file opening operation fails, the return value of the open function is 0. If the file is opened by the constructor, the stream object value is 0. Therefore, no matter which method is used to open the file, you must test whether the file is successfully opened in the program.
After each IO operation on the file ends, you need to close the file, so you need to use the file stream class member function close, generally called form: Stream object. close (); close is actually because the file stream object is lost from the disk file.
2. After opening and closing the file, let's talk about the file read and write. I will introduce the reading and writing of text files and binary files respectively. In fact, it is very easy to read and write files. IO Operations <,>, put, get, getline, read, and write in the stream class library can be used for input and output of files.
(1) read and write text files:
Write File:
1 # include "stdafx. h"
2 # include <iostream>
3 # include <fstream>
4
5 int main ()
6 {
7 // open the file
8 std: ofstream file ("file.txt", std: ios: out | std: ios: ate );
9 if (! File)
10 {
11 std: cout <"file cannot be opened" <std: endl;
12 exit (1 );
13}
14
15 // write a file
16 file <"hello c ++! \ N ";
17
18 char ch;
19 while (std: cin. get (ch ))
20 {
21 if (ch = '\ n ')
22 break;
23 file. put (ch );
24}
25
26 // close the file
27 file. close ();
28
29 return 0;
30}
Keyboard input characters:
 
Read file.txt:
1 # include "stdafx. h"
2 # include <iostream>
3 # include <fstream>
4
5 int main ()
6 {
7 // open the file
8 std: ifstream rfile ("file.txt", std: ios: in );
9 if (! Rfile)
10 {
11 std: cout <"file cannot be opened" <std: endl;
12 exit (1 );
13}
14
15 // read the file
16 char str [100];
17 rfile. getline (str, 100); // read '\ n' to terminate
18 std: cout <str <std: endl;
19
20 char rch;
21 while (rfile. get (rch) // The file Pointer Points to the next of the character '\ N'
22 {
23 std: cout. put (rch );
24}
25
26 std: cout <std: endl;
27
28 // close the file
29 rfile. close ();
30
31 return 0;
32}
Read the display characters:
 
In fact, ios: in and ios: out can be omitted when the ifstream class and ofstream class objects are created, because the ifstream class defaults to ios: in, and the ofstream class defaults to ios: out;
(2) The original design flow is intended for text. Therefore, files are opened in text mode by default. When output in text mode, if the line break "\ n" (decimal: 10) is encountered, it is automatically expanded to the carriage return line break (decimal: 13 and 10 ). Therefore, if we input an integer of 10, the output will be converted to 13 and 10, but this is not what we need. To solve this problem, we need to adopt the binary mode so that the characters written by it are not converted. When I/O operations are performed on binary files, you must specify the ios: binary method for file opening, that is, transfer and storage in binary format. Next, I use the read and write Functions to read and write binary files. Let's briefly introduce the two functions before the example description:
The common format of the read function is: file stream object. read (char * buf, int len );
The common format of the write function is: file stream object. write (const char * buf, int len );
The format is similar. The first parameter is a character pointer, which is used to point to the actual address of the memory space for reading and reading data. The second parameter is an integer that represents the number of bytes of data to be read. The following is an example of binary file read/write:
Define an genie class (for file data processing ):
1 class Sprite
2 {
3 private:
4 std: string regression Sion; // occupation
5 std: string weapon; // weapon
6 static int count; // number
7 public:
8 Sprite (){}
9 Sprite (std: string regression Sion, std: string weapon): Regression Sion (regression sion), weapon (weapon)
10 {
11}
12 void showSprite (); // displays the genie Information
13 };
14
15 int Sprite: count = 0;
16
17 void Sprite: showSprite ()
18 {
19 + + count;
20 std: cout <"Genie" <count <"Occupation:" <strong sion <"weapon:" <weapon <std: endl;
21}
Write File:
1 # include "stdafx. h"
2 # include <iostream>
3 # include <fstream>
4 # include <string>
5
6 int main ()
7 {
8 // create an object Array
9 Sprite sprites [3] = {
10 Sprite ("Mage", "magic wand "),
11 Sprite ("warrior", "tu longbao Dao "),
12 Sprite ("Taoist", "Yi tianjian ")
13 };
14
15 // open the file
16 std: ofstream file ("file. dat", std: ios: ate | std: ios: binary );
17 if (! File)
18 {
19 std: cout <"file opening failed! ";
20 abort (); // equivalent to exit
21}
22
23 // write a file
24 for (int I = 0; I <3; I ++)
25 file. write (char *) & sprites [I], sizeof (sprites [I]);
26
27 // close the file
28 file. close ();
29
30 return 0;
31}
Read file. dat:
1 # include "stdafx. h"
2 # include <iostream>
3 # include <fstream>
4 # include <string>
5
6 int main ()
7 {
8 // create an object Array
9 Sprite rsprites [3];
10
11 // open the file
12 std: ifstream rfile ("file. dat", std: ios: binary );
13 if (! Rfile)
14 {
15 std: cout <"file opening failed! ";
16 return 1; // equivalent to exit
17}
18
19 // read the file
20 for (int I = 0; I <3; I ++)
21 {
22 rfile. read (char *) & rsprites [I], sizeof (rsprites [I]);
23 rsprites [I]. showSprite ();
24}
25
26 // close the file
27 rfile. close ();
28
29 return 0;
30}
Read the display characters:


 
In the read or write functions, data must be converted to the char * type. In the code, the sizeof function is used to determine the number of bytes to be read.
There is an EOF at the end of the file. When reading a file using a file stream, you can use the member function eof () (function prototype: int eof () to detect the ending character. If the return value of this function is non-zero, it indicates that the function reaches the end of the file. If the return value is zero, it indicates that the end of the file is not reached.
(3) All the files mentioned above are read in order. In C ++, the related member functions for file read/write pointers are provided, this allows you to move the file pointer randomly in the IO stream to perform random read/write operations on the file. Istream class provides three member functions for read pointers:
Tellg () // returns the current position of the Input File Read pointer;
Seekg (location in the file) // move the read pointer in the input file to the specified location
Seekg (displacement, reference position) // move several bytes based on the reference position
The reference position is an enumeration value:
Beg // calculate the number of bytes to be moved from the beginning of the file
Cur // calculate the number of bytes to be moved from the current position of the file pointer
End // calculate the number of bytes to be moved from the end of the file
If the reference position is omitted, the default value is beg. Ostream provides three member functions for writing pointers:
Tellp () // returns the current position of the write pointer in the output file;
Seekp (location in the file) // move the write pointer in the output file to the specified location
Seekp (displacement, reference position) // move several bytes based on the reference position
Now I have slightly changed the code for reading binary files in the previous example:
1 # include "stdafx. h"
2 # include <iostream>
3 # include <fstream>
4 # include <string>
5
6 int main ()
7 {
8 // create an object Array
9 Sprite rsprites [3];
10
11 // open the file
12 std: ifstream rfile ("file. dat", std: ios: binary );
13 if (! Rfile)
14 {
15 std: cout <"file opening failed! ";
16 return 1; // equivalent to exit
17}
18
19 // read the file
20 for (int I = 0; I <3; I ++)
21 {
22 rfile. read (char *) & rsprites [I], sizeof (rsprites [I]);
23 rsprites [I]. showSprite ();
24}
25
26 Sprite rsprite; // create an object
27
28 std: cout <"Change read order:" <std: endl;
29 rfile. seekg (sizeof (Sprite) * 2, std: ios: beg); // read the genie Taoist Information
30 rfile. read (char *) & rsprite, sizeof (Sprite ));
31 rsprite. showSprite ();
32
33 rfile. seekg (-int (sizeof (Sprite) * 2), std: ios: end); // read the genie warrior Information
34 rfile. read (char *) & rsprite, sizeof (Sprite ));
35 rsprite. showSprite ();
36
37 rfile. seekg (-int (sizeof (Sprite) * 2), std: ios: cur); // read the wizard Information
38 rfile. read (char *) & rsprite, sizeof (Sprite ));
39 rsprite. showSprite ();
40
41 // close the file
42 rfile. close ();
43
44 return 0;
45}
Result:

 

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.