[fpc-pascal] Open file for append when exists else create new one

LacaK lacak at zoznam.sk
Tue Jul 9 13:08:18 CEST 2019


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

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20190709/b89fa1d1/attachment.html>


More information about the fpc-pascal mailing list