delphidelphi-xe

Create and/or Write to a file


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.


Solution

  • 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);