15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

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

268<br />

Storing Varying Size Data in Untyped Files<br />

Random-access files make it easy to store and retrieve data. Because you<br />

retrieve only the data you want, random-access files don’t waste time reading<br />

the entire file.<br />

Storing Varying Size Data in Untyped Files<br />

Random-access files are great <strong>for</strong> storing chunks of data of equal size.<br />

However, what if you want to store data that may vary in size? You could<br />

define a record as the largest size data you need to store, but that means you<br />

wind up wasting space. As a more efficient alternative, you can store data in<br />

untyped files. Untyped files still organize data in records, but each record can<br />

vary in size, as shown in Figure 8-3.<br />

Figure 8-3:<br />

Untyped<br />

files contain<br />

records that<br />

can vary<br />

in size.<br />

Records can be any size in an untyped file.<br />

Writing data<br />

To store data in an untyped file, you must first name and create an untyped<br />

file. In the Delphi <strong>programming</strong> language, you can create an untyped file by<br />

declaring a variable as a File type, such as<br />

var<br />

myFile : File;<br />

After you create a variable name, you need to assign that variable name to<br />

an actual filename, such as<br />

AssignFile(myFile, ‘MyData.dat’);<br />

In some languages, such as BASIC, you assign a number to an actual filename.<br />

In Delphi and other languages, you assign a name to an actual file. The<br />

purpose of assigning a number or a name is so that you can refer to a file<br />

without typing the complete filename.<br />

Be<strong>for</strong>e you can add any data to an untyped file, use the ReWrite command,<br />

which defines the filename to use and the number of blocks to add to the<br />

file. (Each block of data typically corresponds to one byte of data.) So if you<br />

want to define a 5-byte block of data, you’d use the following:<br />

ReWrite(myFile, 5);

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

Saved successfully!

Ooh no, something went wrong!