vico
vico

Reputation: 18175

Writing to TFileStream

Trying to write characters to TFileStream. Got three garbage characters in file. What I do wrong?

var sss: AnsiString;
var S : TFileStream;
S := TFileStream.Create(FileName,fmCreate);
S.Position := S.Size;
sss := '444';
S.Write(sss,3);
S.Free;

Upvotes: 0

Views: 571

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595377

An AnsiString is implemented as a pointer to its character data. Write() takes a var reference to the data to write. As such, you are writing the pointer itself to your file, not the characters that are being pointed at.

You need to dereference the pointer (ie index into the string) to get a reference to the 1st character, eg:

S.Write(sss[1], Length(sss));

Alternatively:

S.Write(PAnsiChar(sss)^, Length(sss));

That being said, Delphi 2009 and later have a TStreamWriter class that makes this task easier:

var S : TStreamWriter;
S := TStreamWriter.Create(FileName);
S.Write('444');
S.Free;

Upvotes: 5

Related Questions