[Lazarus] Read/Write files question

Kjow antispammoni at gmail.com
Mon Apr 4 16:50:00 CEST 2011


Hi all,

I have a problem with write and read binary files. I can't understand
where I'm in wrong... I hope you can help me.

In a form I have 2 buttons, an edit and a memo.

In the source I made a simple record:

  TCustom1 = record
    Test1: integer;
    Test2: string;
  end;

and then I associated to relative ButtonClicks these codes:

procedure TForm1.Button1Click(Sender: TObject); //this save some data to a file
var
  i: integer;
  TestFile: File of TCustom1;
  Test: TCustom1;
begin
  AssignFile(TestFile,
ExtractFileDir(Application.ExeName)+'/'+Edit1.Text+'.tst');
  Rewrite(TestFile);
  for i:= 0 to 150 do
    begin
      Test.Test1:= i;
      Test.Test2:= ' -> test n° '+IntToStr(Test.Test1)+' <-';
      Write(TestFile, Test);
    end;
  CloseFile(TestFile);
end;

procedure TForm1.Button2Click(Sender: TObject); //this load data from a file
var
  i: integer;
  TestFile: File of TCustom1;
  Test: TCustom1;
begin
  i:= 0;
  Memo1.Clear;
  AssignFile(TestFile,
ExtractFileDir(Application.ExeName)+'/'+Edit1.Text+'.tst');
  Filemode:= fmOpenRead;
  Reset(TestFile);
  while not EOF(TestFile) do
    begin
      inc(i,1);
      Read(TestFile, Test);
      Memo1.Lines.Add('Row '+IntToStr(i)+'°) '+Test.Test2);
    end;
  CloseFile(TestFile);
end;

When I load the file, "i" has the right number of row (e.g. 150), but
I get access violation.

I can't understand where I'm in wrong, if in write or in read or
both... I already used file access, but it worked everytime well...
now I can't make it working.

Thank you,
Kjow

PS Read/write could be used only with records or also with classes?




More information about the Lazarus mailing list