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
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.