19.06.2013 Views

Starting Out with C++: Early Objects - EEMB DERSLER

Starting Out with C++: Early Objects - EEMB DERSLER

Starting Out with C++: Early Objects - EEMB DERSLER

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Binary Files 865<br />

If the data we are writing happens to be character data, there is no need to use the cast.<br />

Here are some examples of writing character data.<br />

char ch = 'X';<br />

char charArray[5] = "Hello";<br />

outFile.write(&ch, sizeof(ch));<br />

outFile.write(charArray, sizeof(charArray));<br />

There is a read member function in the istream and ifstream classes that can be used to<br />

read binary data written by write. It takes as parameters the address of a buffer in which<br />

the bytes read are to be stored, and the number of bytes to read:<br />

read(addressOfBuffer, numberOfBytes)<br />

The address of the buffer must be interpreted as a pointer to char using reinterpret_cast.<br />

You can find out if the specified number of bytes was successfully read by calling the fail()<br />

member function on the input stream.<br />

Program 13-16 demonstrates the use of write and read. The program initializes an array<br />

of integers and then stores the number of array entries in the array using the statements<br />

int buffer[ ] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};<br />

int size = sizeof(buffer)/sizeof(buffer[0]);<br />

Recall that the sizeof operator can be used on variables to determine the number of<br />

bytes occupied by the variable. Here sizeof(buffer) returns the number of bytes allocated<br />

to the array by the initialization statement, and sizeof(buffer[0]) returns the<br />

number of bytes occupied by a single array entry. By dividing the former by the latter, we<br />

obtain the number of array entries, which we then store in size.<br />

Program 13-16 demonstrates the use of write and read.<br />

Program 13-16<br />

1 //This program uses the write and read functions.<br />

2 #include <br />

3 #include <br />

4 using namespace std;<br />

5<br />

6 int main()<br />

7 {<br />

8 // File object used to access file.<br />

9 fstream file("nums.dat", ios::out | ios::binary);<br />

10 if (!file)<br />

11 {<br />

12 cout

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!