Main Page

Previous Page
Next Page

[Page 780 (continued)]

15.5. Unformatted I/O using read, write and gcount

Unformatted input/output is performed using the read and write member functions of istream and ostream, respectively. Member function read inputs some number of bytes to a character array in memory; member function write outputs bytes from a character array. These bytes are not formatted in any way. They are input or output as raw bytes. For example, the call

char buffer[] = "HAPPY BIRTHDAY";
cout.write( buffer, 10 );

[Page 781]

outputs the first 10 bytes of buffer (including null characters, if any, that would cause output with cout and << to terminate). The call


displays the first 10 characters of the alphabet.

The read member function inputs a designated number of characters into a character array. If fewer than the designated number of characters are read, failbit is set. Section 15.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 15.7 demonstrates istream member functions read and gcount and ostream member function write. The program inputs 20 characters (from a longer input sequence) into character array buffer with read (line 15), determines the number of characters input with gcount (line 19) and outputs the characters in buffer with write (line 19).

Figure 15.7. Unformatted I/O using the read, gcount and write member functions.

 1  // Fig. 15.7: Fig15_07.cpp
 2  // Unformatted I/O using read, gcount and write.
 3  #include <iostream>
 4  using std::cin;
 5  using std::cout;
 6  using std::endl;
 8  int main()
 9  {
10     const int SIZE = 80;
11     char buffer[ SIZE ]; // create array of 80 characters
13     // use function read to input characters into buffer
14     cout << "Enter a sentence:" << endl;
15     cin.read( buffer, 20 );
17     // use functions write and gcount to display buffer characters
18     cout << endl << "The sentence entered was:" << endl;
19     cout.write( buffer, cin.gcount() );
20     cout << endl;
21     return 0;
22  } // end main

 Enter a sentence:
 Using the read, write, and gcount member functions
 The sentence entered was:
 Using the read, writ

Previous Page
Next Page