Create and/or Write to a file

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

    Any solution that uses FileExists to choose how to open the file has a race condition. If the file's existence changes between the time you test it and the time you attempt to open the file, your program will fail. Delphi doesn't provide any way to solve that problem with its native file I/O routines.

    If your Delphi version is new enough to offer it, you can use the TFile.Open with the fmOpenOrCreate open mode, which does exactly what you want; it returns a TFileStream.

    Otherwise, you can use the Windows API function CreateFile to open your file instead. Set the dwCreationDisposition parameter to OPEN_ALWAYS, which tells it to create the file if it doesn't already exist.

提交回复
热议问题