Create and/or Write to a file

前端 未结 5 1114
逝去的感伤
逝去的感伤 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 02:02

    You can also use the load/save feature in a TStringList to solve your problem.

    This might be a bad solution, because the whole file will be loaded into memory, modified in memory and then saved to back to disk. (As opposed to your solution where you just write directly to the file). It's obviously a bad solution for multiuser situations.

    But this approach is OK for smaller files, and it is easy to work with and easy understand.

    const
      FileName = 'test.txt';
    var
      strList: TStringList;
    begin
      strList := TStringList.Create;
    
      try
        if FileExists(FileName) then
          strList.LoadFromFile(FileName);
    
        strList.Add('My new line');
    
        strList.SaveToFile(FileName);
      finally
        strList.Free;
      end;
    end;
    

提交回复
热议问题