Pascal · lesson 26 of 30 · Tools for the NASCopy a file with a date
FormatDateTime makes the name and TFileStream copies the file.
26-dated-backup.pas Download 26-dated-backup.pas
program DatedBackup;
{$mode objfpc}{$H+}
{ Copies one file into backups/ under a name with the date and time }
uses
SysUtils, Classes;
var
Source, Target: string;
InFile, OutFile: TFileStream;
begin
Source := ParamStr(1);
if not FileExists(Source) then
begin
WriteLn('There is no file ', Source);
Halt(1);
end;
ForceDirectories('backups');
Target := 'backups/' + ChangeFileExt(ExtractFileName(Source), '')
+ FormatDateTime('-yyyy-mm-dd-hhnnss', Now) + ExtractFileExt(Source);
if FileExists(Target) then
begin
WriteLn('There is ', Target, ' already');
Halt(1);
end;
InFile := TFileStream.Create(Source, fmOpenRead or fmShareDenyWrite);
try
OutFile := TFileStream.Create(Target, fmCreate);
try
WriteLn(OutFile.CopyFrom(InFile, 0), ' bytes to ', Target);
finally
OutFile.Free;
end;
finally
InFile.Free;
end;
end.
Terminal
$ ./26-dated-backup words.txt
87 bytes to backups/words-2026-11-25-140800.txt
$ ls backups
words-2026-11-25-140800.txt
$ cmp words.txt backups/words-*.txt && echo "the copy is the same"
the copy is the sameThe numbers or the date differ on your NAS.
Exercise
Stop if the backup is already there.