vfclists
vfclists

Reputation: 20251

How can I use TFileStream to truncate the existing file before overwriting it?

I am using the code below to write to an existing file, but the contents get appended. What TFileStream options are necessary to empty the file and overwrite it?

procedure TUtilitiesForm.btnSaveClick(Sender: TObject);
var fs: TFileStream;
begin
  fs := TFileStream.Create(FileNameEdit1.Text, fmOpenWrite);
  fs.Seek(0,fsFromEnd);
  mmoDDL.Lines.SaveToStream(fs);
  fs.Free;
end;

Upvotes: 1

Views: 965

Answers (1)

Joao Morais
Joao Morais

Reputation: 1935

Using fsFromEnd you append data beyond the end of an existing file, on the other hand fsFromBeginning starts from the beginning but won't truncate the file.

Change from fmOpenWrite to fmCreate

procedure TUtilitiesForm.btnSaveClick(Sender: TObject);
var fs: TFileStream;
begin
  fs := TFileStream.Create(FileNameEdit1.Text, fmCreate);
  try
    mmoDDL.Lines.SaveToStream(fs);
  finally
    FreeAndNil(fs);
  end;
end;

Upvotes: 3

Related Questions