Unformatted input/output is performed using the read and write member functions of istream
and ostream
, respectively. Member function read
inputs bytes to a built-in array of char
s in memory; member function write
outputs bytes from a built-in array of char
s. These bytes are not formatted in any way. They’re input or output as raw bytes. For example, the call
outputs the first 10 bytes of buffer
(including null characters, if any, that would cause output with cout
and <<
to terminate). The call
cout.write( "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 10 );
displays the first 10 characters of the alphabet.
The read
member function inputs a designated number of characters into a built-in array of char
s. If fewer than the designated number of characters are read, failbit
is set. Section 13.8 shows how to determine whether failbit
has been set. Member function gcount reports the number of characters read by the last input operation.
Figure 13.7 demonstrates istream
member functions read
and gcount
, and ostream
member function write
. The program inputs 20 characters (from a longer input sequence) into the array buffer
with read
(line 13), determines the number of characters input with gcount
(line 17) and outputs the characters in buffer
with write
(line 17).
1 // Fig. 13.7: fig13_07.cpp
2 // Unformatted I/O using read, gcount and write.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 const int SIZE = 80;
9 char buffer[ SIZE ]; // create array of 80 characters
10
11 // use function read to input characters into buffer
12 cout << "Enter a sentence:" << endl;
13 cin.read( buffer, 20 );
14
15 // use functions write and gcount to display buffer characters
16 cout << endl << "The sentence entered was:" << endl;
17 cout.write( buffer, cin.gcount() );
18 cout << endl;
19 } // end main
Enter a sentence:
Using the read, write, and gcount member functions
The sentence entered was:
Using the read, writ