C ++ I/O Stream class library (3): file read/write, binary file read/write, random file read/write

Source: Internet
Author: User

I. file read/write

As mentioned above, stream reads and writes mainly include <,>, get, put, read, write, and other operations. ofstream inherits from ostream, and ifstream inherits from istream, therefore, the operation functions are consistent.

C ++ code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# Include <iostream>
# Include <fstream>
# Include <string>
# Include <cassert>
Using namespace STD;

Int main (void)
{
Ofstream fout ("test.txt ");
Fout <"ABC" <"<200;
Fout. Close ();

Ifstream fin ("test.txt ");
String S;
Int N;
// Fin> N> S;
Fin> S> N;
Cout <S <"" <n <Endl;

Ofstream fout1 ("test2.txt ");
Assert (fout1 );
Char ch;

For (INT I = 0; I <26; I ++)
{
Ch = 'A' + I;
Fout1.put (CH );
}
Fout1.close ();

Ifstream fin1 ("test2.txt ");
While (fin1.get (CH ))
{
Cout <ch;
}
Cout <Endl;

Return 0;
}

Ii. Binary file read/write

Binary files, unlike text files, can be used for any type of files (including text files)
The read and write operations on binary files can be performed using the member function read () inherited from the istream class and the member function write () inherited from the ostream class ()
When opening a file, use the enumerated constant IOs: binary, for example, ofstream fout ("binary. dat", IOS: Out | IOs: Binary );


(1) Write member functions

Function: writes the entire data block to the file stream in bytes. The most valuable application can process struct variables and class objects.
Function prototype:

Ostream & write (const char * PCH, int ncount );

Function parameters:
Pointer to data written by PCH
The size of data written by ncount in bytes


(2) read member functions

Function: Read the entire data block from the file stream.
Function prototype:

Istream & read (char * PCH, int ncount );

Function parameters:
PCH pointer used to receive data
Size of the number of bytes read by ncount


C ++ code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Include <cassert>
# Include <iostream>
# Include <fstream>
# Include <string>

Using namespace STD;

Struct Test
{
Int;
Int B;
};

Int main (void)
{
Ofstream fout ("test3.txt", IOS: Out | IOs: Binary); // enable it in binary mode. '\ n' is not converted.
Fout <"ABC \ n"; // <is written as text
Fout. Close ();

Test test = {100,200 };
Ofstream fout1 ("test4.txt", IOS: Out | IOs: Binary );
Fout1.write (reinterpret_cast <char *> (& test), sizeof (TEST ));
// After the two-step method is written, use the render editor to open the test4.txt Garbled text.
Fout1.close ();

Test Test2;
Ifstream fin ("test4.txt", IOS: In | IOs: Binary );
Fin. Read (reinterpret_cast <char *> (& Test2), sizeof (TEST ));
Cout <test2.a <"" <test2. B <Endl;

Ofstream fout2 ("test5.txt", IOS: Out | IOs: Binary );
Fout2 <"ABC" <200; // <writes data in text format.
Fcout2.close ();

Return 0;
}

Open the file in text mode in the window, and then encounter '\ n' when writing, convert it to' \ r \ n', and open it in binary format without conversion. Therefore, the size of the test3.txt file is 4 bytes.

Write 100 (write is written in binary format) is no longer the ASCII code of '1', '0', and '0', but it is written in the form based on the memory, so garbled characters may occur when the producer Editor opens test4.txt. The file size is 8 bytes (two int values)

Likewise, although test5.txt is opened in binary format, it is written in text format (<written in text format). Therefore, after being written in 200, it will not contain garbled characters when opened in a text editor. The file size is 6 bytes.

For the differences between text files and binary files, see here.


When reading a string using read and write, note that the string is actually a pointer member, sizeof (string) = 32 (related to compiler implementation), that is, the string size is certain, the length of the string stored by its pointer members is not necessarily 32, so we should read and write these:

C ++ code
1
2
3
4
5
6
7
8
9
String str1 = "fdsfafsdsf ";
Int Len = str1.length ();
Ofstream fout ("test6.txt", IOS: Out | IOs: Binary );
Fout. Write (str1.data (), str1.length ());

String str2;
Str2.resize (LEN );
Ifstream fin ("test6.txt", IOS: In | IOs: Binary );
Fin. Read (& str2 [0], Len );

If you write data to fout like this. write (char *) & str1, sizeof (str1); it must be incorrect because it is written to the str1 pointer member rather than the string pointed to by the pointer member, in addition, the size of str1 is always equal to 32.


Iii. Random file read/write

(1) activity pointer of the current file stream

The file stream pointer is used to track the locations where I/O operations occur.
Each time a character is read or written from the stream, the current active pointer moves forward.
When the open mode does not include the IOS: ate or IOS: app option, the file pointer is automatically moved to the start position of the file, that is, the byte address is 0.


(2) random read/write seekp and seekg of Files

Seekp and seekg are similar to fseek of C library and lseek called by Linux system.


Function

Seekp: Set the file stream pointer position of the output file stream

Seekg: Set the file stream pointer position of the input file stream

Function prototype:

Ostream & seekp (streampos POS );

Ostream & seekp (streamoff off, IOS: seek_dir DIR );

Istream & seekg (streampos POS );

Istream & seekg (streamoff off, IOS: seek_dir DIR );

Function Parameters

POs: New file stream pointer position value

Off: value to be offset

Dir: Start position of the search

The dir parameter is used to locate the file stream pointer, representing the start position of the search.
Enumeration type defined in IOS:

Enum seek_dir {beg, cur, end };

Meanings of each enumerated constant:
IOS: Beg: Start position of the file stream
IOS: cur: current location of the file stream
IOS: end: the end position of the file stream


Tellp and tellg are similar to the ftell of the c library, and the lseek (FD, 0, seek_cur) called by the Linux system );

Function

Tellp: the current position of the output file stream pointer, in bytes

Tellg: obtains the current position of the input file stream pointer, in bytes.

Function prototype:

Streampos tellp ();

Streampos tellg ();

Function return value: it is actually a long type.


C ++ code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Include <cassert>
# Include <iostream>
# Include <fstream>
# Include <string>

Using namespace STD;

Int main (void)
{
Ifstream fin ("test7.txt ");
Assert (FIN );
Fin. seekg (2); // The position starts from 0.

Char ch;
Fin. Get (CH );
Cout <ch <Endl;

Fin. seekg (-1, IOS: End); // The end is actually an EOF location.
Fin. Get (CH );
Cout <ch <Endl;

Fin. seekg (0, IOS: End );
Streampos Pos = fin. tellg ();
Cout <POS <Endl;

Return 0;
}

Assume that test7.txt contains seven abcdefg characters, and the output is c g 7.


Refer:

C ++ primer version 4
Valid tive C ++ 3rd
C ++ programming specifications

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.