Trying to understand TFileStream

From: Dan Combs (dancombs2_at_verizon.net)
Date: 04/29/04


Date: Thu, 29 Apr 2004 00:57:54 GMT

I make a class with two strings:

  TGameComponent = class
    name: string;
    description: string;
    procedure setName(s: string);
    procedure setDescription(s: string);
    function getName: string;
    function getDescription: string;
  end;

I use the class on a form with two buttons, two edit boxes, and two labels:

  TForm1 = class(TForm)
    Edit1: TEdit;
    Button1: TButton;
    Label1: TLabel;
    Edit2: TEdit;
    Label2: TLabel;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);

The first button makes an instance of the class and tries to save it to a
file:

procedure TForm1.Button1Click(Sender: TObject);
var
  game: TGameComponent;
  f: TFileStream;
  size: longint;
begin
  game:=TGameComponent.Create;
  game.setName(edit1.Text);
  game.setDescription(edit2.Text);
  f:= TFileStream.Create('test.dat', fmCreate);
  size:=game.InstanceSize;
  f.Write(game, size);
  f.Destroy;
  game.setName(' ');
  game.setDescription(' ');
end;

The second button tries to retrieve the class from the file:

procedure TForm1.Button2Click(Sender: TObject);
var
  game: TGameComponent;
  f: TFileStream;
  size: longint;
begin
  game:=TGameComponent.Create;
  f:= TFileStream.Create('test.dat', fmOpenRead);
  size:=f.Size;
  f.Read(game, size);
  f.Destroy;
  label1.caption := game.getName;
  label2.Caption := game.getDescription;
end;

The end result is the strings are not being retrieved from the file. Can
anyone tell me what I am doing wrong?

Thanks

Dan Combs


Quantcast