Delphi tfilestream.readbuffer fails to read string value from file

1.7k Views Asked by At

I am reading and writing data from a file using a filestream but am having a problem reading strings from my file.

In a test VCL form program I have written:

procedure tform1.ReadfromFile4;
  var
  fs: TFileStream;
  arrayString: Array of String;
  i, Len1 : Cardinal;
//  s : string;
begin
  fs := TFileStream.Create('C:\Users\Joe\Documents\Delphi\Streamtest.tst',
                 fmOpenRead or fmShareDenyWrite);
  Memo1.lines.clear;

  try
    fs.ReadBuffer(Len1, SizeOf(Len1));
    SetLength(arrayString, Len1);
    FOR i := 0 to Len1-1 do begin
      fs.ReadBuffer(Len1, SizeOf(Len1));
      SetLength(arrayString[i], Len1);
      Fs.ReadBuffer(arrayString[i], Len1);
      memo1.lines.add (arrayString[i]);
    end;
  finally
    fs.free;
  end;
end;

procedure tform1.WriteToFile4;
var
  fs: TFileStream;
  arrayString: Array of String;
  Len1, c, i: Cardinal;
begin
  Memo1.lines.clear;
  SetLength(arrayString, 4);
  arrayString[0] := 'First string in this Array';
  arrayString[1] := 'the Second Array string';
  arrayString[2] := 'String number three of this Array';
  arrayString[3] := 'this is the fourth String';
  fs := TFileStream.Create('C:\Users\Joe\Documents\Delphi\Streamtest.tst',
                 fmCreate or fmOpenWrite or fmShareDenyWrite);
  try
    c := Length(arrayString);
    Fs.WriteBuffer(c, SizeOf(c));
    for i := 0 to c-1 do begin
      Len1 := Length(arrayString[i]);
      fs.WriteBuffer(Len1, SizeOf(Len1));
      if Len1 > 0 then begin
        fs.WriteBuffer(arrayString[i], Len1);

      end;
    end;
  finally
    fs.free;
  end;

end;

The Save button action enters the four strings correctly, but the Load button (readFromFile4) fails to load the strings from the file. Using the Watch list, I find that the string lengths are set correctly for each string, but the data accessed is not the correct string values. I believe I am faithfully following the instructions on the website : http://www.angelfire.com/hi5/delphizeus/customfiles.html]1 in the section titled

Writing and Reading Dynamic Arrays of Non-Fixed Size Variables

Can anyone shed light on why this does not read the strings from the file correctly?

0

There are 0 best solutions below