With TStringStream, the bytes using its Bytes property differs from the bytes extracted using TStream.Read. As shown below:
- the
bytesextracted usingTStream.Readrepresents correct data. - the
bytesusing itsBytesproperty contains more data.(the last byte of correctbytesis different from that of wrongbytes)
Could you help to comment about the possible reason? Thank you very much for your help!
PS: Delphi XE, Windows 7. (It seems TStringStream back in Delphi 7 doesn’t have LoadFromFile or SaveToFile.)
PS: The sample files can be download from SkyDrive: REF_EncodedSample & REF_DecodedSample. (Zlib-compressed image file.).
procedure CompareBytes_2;
var
ss_1: TStringStream;
ss_2: TStringStream;
sbytes_Read: TBytes;
sbytes_Property: TBytes;
len_sbytes_Read: Integer;
len_sbytes_Property: Integer;
filename: string;
begin
filename := 'REF_EncodedSample'; // textual data
// filename := 'REF_DecodedSample'; // non-textual data
ss_1 := TStringStream.Create;
ss_1.LoadFromFile(filename);
ss_2 := TStringStream.Create;
ss_2.LoadFromFile(filename);
ss_1.SaveToFile(filename+ '_CopyByStringStream_1');
ss_2.SaveToFile(filename+ '_CopyByStringStream_2');
len_sbytes_Read := ss_1.Size;
SetLength(sbytes_Read, len_sbytes_Read);
ss_1.Read(sbytes_Read[0], len_sbytes_Read);
sbytes_Property := ss_2.Bytes;
ShowMessage(
BoolToStr(
Length(sbytes_Read) = Length(sbytes_Property),
True));
ShowMessage(
BoolToStr(
sbytes_Read[len_sbytes_Read - 1] = sbytes_Property[len_sbytes_Read - 1],
True));
ss_1.Free;
ss_2.Free;
end;
The string stream documentation states:
Presumably the buffer has been allocated to hold more space than it actually needs. Only the first Size bytes of the buffer contain valid content.
Also, the call to ss_1.Read is a little pointless since Length(sbytes_Read) does not change after the call to SetLength. And when reading from a stream you are to use ReadBuffer rather than Read. Likewise for WriteBuffer.