Re: Re: reading/writing to typed files


Posted by webmaster Guido on April 11, 2001 at 00:00:29:

In Reply to: Re: reading/writing to typed files posted by James on April 10, 2001 at 00:09:08:

: : My project is to:-
: : a. create a typed file and add several records to it.
: : b. at a later date, retrieve a specific record and update it.
: : I have only managed to create and add 1 record. Every time i try to add a new record, it overwrites the first one.
------------
: I looked up "append" in the help section of the program, and heres what it said:
: "procedure Append(var F: Text);
: Description
: Call Append to ensure that a file is opened with write-only access with the file pointer positioned at the end of the file. F is a text file variable and must be associated with an external file using AssignFile"
: So, just use Append instead of Writeln
: James
----------

Tony, since you say that you can write one record, we only have to concentrate on appending and replacing records. If you'd give us the code that you're currently using for this, we could maybe spot the problem area.

Firstly, allow me to correct the previous answer: the question was not about "text" files, but "typed" files, files of records. The definition of the record type usually goes in a "global" part of the unit, so that all procedures and functions can access it:

type TCar = record   
  ID: string[6];   
  Name: string[8];
  OwnIt: Boolean;  
end; 

The procedure for adding a record could look like this:

procedure AddACar(CarToAdd: TCar; FileName: string);
var
 F: file of TCar;
begin
 AssignFile(F, FileName);
 Reset(F);
 Seek(F, FileSize(F));
 Write(F, CarToAdd);
 CloseFile(F);
end; 

You would add a record to the file C:\Temp\MyCars.dat as follows:

procedure TForm1.BtnAddCorvetteClick(Sender: TObject);
var
  MyDreamCar: TCar;
begin 
  MyDreamCar.ID := '000001';
  MyDreamCar.Name := 'Corvette';
  MyDreamCar.OwnIt := False;
  AddACar(MyDreamCar, 'C:\Test\MyCars.dat');
end;
  

Important note: to keep the examples short and clear, I omitted all the error checking stuff, such as "Does the file exist?"