Create and/or Write to a file

Eric G picture Eric G · Oct 20, 2011 · Viewed 63.8k times · Source

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.

Answer

RRUZ picture RRUZ · Oct 20, 2011

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