Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the TFileStream equivalent to pascal IO Append(F)?

Tags:

delphi

I assume it is:

FS := TFileStream.Create(FileName, fmOpenReadWrite);
FS.Seek(0, soFromEnd); 

Is that correct? is the open mode correct or maybe fmOpenWrite or need to add fmShareDenyNone?

PS: For Rewrite(F) I used FS := TFileStream.Create(FileName, fmCreate);


Based on @David's comments I ended up using THandleStream

procedure LOG(const FileName: string; S: string);
const
  FILE_APPEND_DATA = 4;
  OPEN_ALWAYS = 4;
var
  Handle: THandle;
  Stream: THandleStream;
begin
  Handle := CreateFile(PChar(FileName),
    FILE_APPEND_DATA, // Append data to the end of file
    0, nil,
    OPEN_ALWAYS, // If the specified file exists, the function succeeds and the last-error code is set to ERROR_ALREADY_EXISTS (183).
                 // If the specified file does not exist and is a valid path to a writable location, the function creates a file and the last-error code is set to zero.
    FILE_ATTRIBUTE_NORMAL, 0);

  if Handle <> INVALID_HANDLE_VALUE then
  try
    Stream := THandleStream.Create(Handle);
    try
      S := S + #13#10;
      Stream.WriteBuffer(S[1], Length(S) * SizeOf(Char));
    finally
      Stream.Free;
    end;
  finally
    FileClose(Handle);
  end
  else
    RaiseLastOSError;
end;
like image 672
zig Avatar asked Jan 27 '26 04:01

zig


1 Answers

Actually it would be

FStream := TFileStream.Create(Filename, fmOpenWrite);
FStream.Seek(0, soEnd);

You can see an example in TBinaryWriter.Create or TStreamWriter.Create - or you just opt to use one of these classes directly.

like image 103
Uwe Raabe Avatar answered Jan 29 '26 21:01

Uwe Raabe