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

时间:2017-01-10 09:51:38

标签: delphi

我认为是:

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

这是对的吗?开放模式是正确的还是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;

2 个答案:

答案 0 :(得分:4)

实际上它会是

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

您可以在TBinaryWriter.CreateTStreamWriter.Create中查看示例 - 或者您只是选择直接使用其中一个类。

答案 1 :(得分:1)

应该是这样的

var
  FileName: string;
  FS: TFileStream;
  sOut: string;
  i: Integer;
  Flags: Word;
begin
  FileName := ...; // get your file name from somewhere
  Flags := fmOpenReadWrite;
  if not FileExists(FileName) then
    Flags := Flags or fmCreate;
  FS := TFileStream.Create(FileName, Flags);
  try
    FS.Position := FS.Size;  // Will be 0 if file created, end of text if not
    sOut := 'This is test line %d'#13#10;
    for i := 1 to 10 do
    begin
      sOut := Format(sOut, [i]);
      FS.Write(sOut[1], Length(sOut) * SizeOf(Char)); 
    end;

  finally
    FS.Free;
  end;
end;

此代码还验证文件是否不存在,如果不存在则创建该文件。

关于标志,您可以在documentation

中找到每个标志的定义
相关问题