Create and/or Write to a file

前端 未结 5 1051
逝去的感伤
逝去的感伤 2021-02-07 01:26

I feel like this should be easy, but google is totally failing me at the moment. I want to open a file, or create it if it doesn\'t exist, and write to it.

The followin

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-07 01:53

    You should be using TFileStream instead. Here's a sample that will create a file if it doesn't exist, or write to it if it does:

    var
      FS: TFileStream;
      sOut: string;
      i: Integer;
      Flags: Word;
    begin
      Flags := fmOpenReadWrite;
      if not FileExists('D:\Temp\Junkfile.txt') then
        Flags := Flags or fmCreate;
      FS := TFileStream.Create('D:\Temp\Junkfile.txt', 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;
    

提交回复
热议问题