与 pascal IO Append(F) 等效的 TFileStream 是什么?

zig*_*zig 2 delphi

我认为是:

FS := TFileStream.Create(FileName, fmOpenReadWrite);
FS.Seek(0, soFromEnd); 
Run Code Online (Sandbox Code Playgroud)

那是对的吗?打开模式是否正确或者可能fmOpenWrite或需要添加fmShareDenyNone

PS:对于Rewrite(F)我用过的FS := TFileStream.Create(FileName, fmCreate);


根据@David 的评论,我最终使用了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;
Run Code Online (Sandbox Code Playgroud)

Uwe*_*abe 5

其实它会是

FStream := TFileStream.Create(Filename, fmOpenWrite);
FStream.Seek(0, soEnd);
Run Code Online (Sandbox Code Playgroud)

TBinaryWriter.Create您可以在或中查看示例TStreamWriter.Create- 或者您只需选择直接使用这些类之一。

  • 取决于Delphi版本。在柏林,我们有 `TSeekOrigin = (soBeginning, soCurrent, soEnd);` 因为您没有指定任何版本,所以我通常假设当前版本。 (3认同)