02.07.2013 Views

The turbo

The turbo

The turbo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Part 2 Chapter 18 Files<br />

Now, to save the information in Ship, you could write:<br />

Assign(ShipFlle,'SHIPS.DAT');<br />

Rewrite(ShipFlle );<br />

Write( ShipFlle,Ship);<br />

Close(ShipFlle);<br />

Simple, isn't it? With a single Write statement, you have sent all<br />

the ship records out to the disk. To read it back in, you just write:<br />

Assign(ShipFlle,'SHIPS.DAT');<br />

ResetCShipFile);<br />

Read(Ship:B'ile,Ship );<br />

Close(ShipFile);<br />

Unfortunately, you've now lost track of one piece of information,<br />

namely the value of ShipCnt. However, there are a number of<br />

ways around this. First, you could redefine ShipArray to be a<br />

record with two fields: the ship count and the array itself. Second,<br />

you could save the value of ShipCnt in another file, either by itself<br />

or as part of another data structure. Third, you could add another<br />

field to the definition of AShip which would indicate whether or<br />

not that record was, indeed, a "real" ship; then, after you've read<br />

Ship in, you just go through and count all of the records with that<br />

value set. Finally, you could rewrite the game so that the value<br />

ShipCnt is no longer needed.<br />

18.1 RANDOM ACCESS OF FILES<br />

From what you've seen so far, to read or write a particular record<br />

in a file, you must go to the start of the file and work from there. If<br />

you wish to read the 10th record in a file, you must reset the file<br />

and go through the first nine records to get to the tenth. If you<br />

want to modify the tenth record, you must read it in as mentioned,<br />

reset the file, read in the first nine, then write the 10th back out. In<br />

short, a lot of work.<br />

18-5

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

Saved successfully!

Ooh no, something went wrong!