unit dsafefileupdate;

//
//  Functions for safe updating of file content.
//

{$MODE FPC}
{$MODESWITCH DEFAULTPARAMETERS}
{$MODESWITCH OUT}
{$MODESWITCH RESULT}

interface

uses
  dfiles,
  dfilewriter;

function SafeFileUpdate(const FileName: AnsiString;
                        Content: Pointer;
                        ContentLen: SizeUInt;
                        TempFileName: AnsiString = ''): Boolean;
      //
      //  1. Tries to dump content to the file TempFileName.
      //  2. Tries to move the file TempFileName to the file FileName.
      //
      //  If the value TempFileName is empty, then FileName+'.tmp' is used.
      //
      //  If True returned, the FileName contains new content.
      //  Otherwise error was occured and the file FileName is unchanged.
      //
      //  Status of TempFileName is undefined if error occured.
      //

implementation

function SafeFileUpdate(const FileName: AnsiString;
                        Content: Pointer;
                        ContentLen: SizeUInt;
                        TempFileName: AnsiString = ''): Boolean;
begin
  if TempFileName = '' then
    TempFileName := FileName + '.tmp';
  Result := WriteFileContent(TempFileName, Content, ContentLen)
        and FileRename(TempFileName, FileName);
  if Result then
    FileRemove(TempFileName);
end;

end.
