|
To access the contents, click the chapter and section titles.
Learn Pascal in a Three Days (2nd Ed.)
Storing Lists in FilesTo store a linked list in a file, follow the following steps:
The following program segment summarizes the preceding steps: VAR CurrentPointer:ListPointer; BEGIN ASSIGN(MyListFile, FileName); REWRITE(MyListFile); CurrentPointer:= FirstPointer; WHILE CurrentPointer <> NIL DO BEGIN WRITE(MyListFile, CurrentPointer^.DataField); CurrentPointer:= CurrentPointer^.NextField END; CLOSE(MyListFile) END; Reading Lists from FilesWhen you store a linked list in a file, you only store the data. The list pointers are only used in memory to control the list. Therefore, when the file is written to the disk, it becomes a regular data file, and may be read using the regular procedures. After reading the file, it is your preference to build the data as a linked list. To add the data read from a file to a linked list, do the following:
Example: A List of RecordsIn this section, you are going to work with a more practical linked list, a list of employee records. Look at these types: TYPE {Declaration of data type } SSNstring = STRING[11]; DataRecord = RECORD ID :STRING[5]; Name, Position :STRING[20]; SSN :SSNstring; Rate :REAL END; {Declaration of the list } ListPointer = ^ListRecord; ListRecord = RECORD DataField:DataRecord; NextField:ListPointer END; EmpFile = FILE OF DataRecord; These declarations are divided into two main parts:
Note in these declarations that the SSNstring type comes first, because it is used in the definition of the employee record (DataRecord). Note also that the data field (DataField) in the linked list is of the type DataRecord. A file of DataRecords, in which you are going to store the list, is also defined. Using a file of records makes the file handling much easier. The global variables you are going to use are a list pointer, a file variable, and a record variable: VAR FirstPointer:ListPointer; MyListFile :EmpFile; EmpRecord :DataRecord; When you deal with a list of records, use the same procedures used with simple lists, because you are still dealing with nodes. Only remember to use fielded variables to read the fields. For example, in a list of strings you refer to each string using the variable CurrentPointer^.DataField In a list of records, you refer to the SSN field (as an example) using the variable CurrentPointer^.DataField.SSN or you may use a WITH statement to do the same thing: WITH CurrentPointer^.DataField DO BEGIN WRITE(ID:7); WRITE(Name:22);...
|
Products | Contact Us | About Us | Privacy | Ad Info | Home
Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc. All rights reserved. Reproduction whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement. |