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 following
AssignFile(logFile, 'Test.txt'); Append(logFile);
throws an error on the second line when the file doesn't exist yet, which I assume is expected. But I'm really failing at finding out how to a) test if the file exists and b) create it when needed.
FYI, working in Delphi XE.
java File file = new File("JavaFile. java"); We then use the createNewFile() method of the File class to create new file to the specified path.
You can use the FileExists
function and then use Append
if exist or Rewrite
if not.
AssignFile(logFile, 'Test.txt'); if FileExists('test.txt') then Append(logFile) else Rewrite(logFile); //do your stuff CloseFile(logFile);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With