Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2019-07

Open file for append when exists else create new one

1 message · 1 person ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

LacaK

Hi,

I want to achieve this:

If file with given name already exists then open it for append else create new one and open it for append.

I use something like:

   FileName:='FileName'+formatdatetime('yymmdd',date)+'.log';
   if FileExists(FileName) then F:=FileOpen(FileName,
fmOpenWrite+fmShareDenyWrite) else F:=FileCreate(FileName);
   FileSeek(F, 0, 2); //... 0 bytes from the end of the file
   FileWrite(F, Pointer(s)^, length(s));
   FileClose(F);

or:

   if FileExists(FileName) then
     FS := TFileStream.Create(FileName, fmOpenWrite+fmShareDenyWrite)
   else
     FS := TFileStream.Create(FileName, fmCreate+fmShareDenyWrite);
   FS.Seek(0, soEnd);
   FS.Write(s[1], Length(s));
   FS.Free;

Is there way how to achieve this using one-line without checking FileExists ? i.e.:
resulting efect like when using on Windows CreateFile(FileName, GENERIC_WRITE, FILE_SHARE_READ, *OPEN_ALWAYS,*...)* CreationDisposition =  OPEN_ALWAYS - Opens a file, always if exists else create new one.
If the specified file exists, the function succeeds and the last-error code is set to ERROR_ALREADY_EXISTS (183).
If the specified file does not exist and is a valid path to a writable location, the function creates a file and the last-error code is set to zero.*

L.
**

Reply by email