Question : Problem by using TFileStream:   Save and Read ShortString in Delphi2010

hello all,

i have tried to save 'ABCDEFGHIJ' as ShortString in a file, when i read it from the file , i get
'ABCDEFGHIJ\ö '. It seems there are more sysbols come out.

following are my codes, how should i change it to make it work?

any tips are appreciated.

thanks,

wantime
-------------------------------------------------------------
--------------------------------------------------------------
procedure TForm1.LoadShortStingClick(Sender: TObject);
var
  ID: String[10];
begin
  aStream := TFileStream.Create(mpath, fmOpenRead);
  aStream.Read(ID[1], 10);
  Edit2.text := ID;
  aStream.Free;
end;

procedure TForm1.SaveShortStingClick(Sender: TObject);
var
  S: String[10];
begin

  S[1] := 'A';
  S[2] := 'B';
  S[3] := 'C';
  S[4] := 'D';
  S[5] := 'E';
  S[6] := 'F';
  S[7] := 'G';
  S[8] := 'H';
  S[9] := 'I';
  S[10] := 'J';

  aStream := TFileStream.Create(mpath, fmCreate);
  aStream.Write(S[1], 10);

  aStream.Free;
end;

Answer : Problem by using TFileStream:   Save and Read ShortString in Delphi2010

In Delphi2009 and newer (so yours too), string is no longer 1 byte per char, but multiple bytes.

So, while
var
 ID:  String[10];

Looks like an array of 10 bytes, it's not.

So if you do
  aStream.Read(ID[1], 10);

You read 10 bytes into an array which is longer then 10 bytes. Result is that you don't know what is in the rest of the array. There is probably some crap in there which is interpreted as a string when you try to put it in the edit.
Random Solutions  
 
programming4us programming4us