Baza wiedzy NASutilsNieoficjalnaEnglish

Pascal · lekcja 26 z 30 · Narzędzia dla NAS-aSkopiuj plik z datą

FormatDateTime tworzy nazwę, a TFileStream kopiuje plik.

Programowanie na NAS-ie › Pascal w 30 lekcjach

26-dated-backup.pas Pobierz 26-dated-backup.pas

program DatedBackup;
{$mode objfpc}{$H+}
{ Kopiuje jeden plik do backups/ pod nazwą z datą i godziną }
uses
  SysUtils, Classes;
var
  Source, Target: string;
  InFile, OutFile: TFileStream;
begin
  Source := ParamStr(1);
  if not FileExists(Source) then
  begin
    WriteLn('Nie ma pliku ', 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('Plik ', Target, ' już istnieje');
    Halt(1);
  end;
  InFile := TFileStream.Create(Source, fmOpenRead or fmShareDenyWrite);
  try
    OutFile := TFileStream.Create(Target, fmCreate);
    try
      WriteLn(OutFile.CopyFrom(InFile, 0), ' B skopiowano do ', Target);
    finally
      OutFile.Free;
    end;
  finally
    InFile.Free;
  end;
end.

Terminal

$ ./26-dated-backup words.txt
87 B skopiowano do backups/words-2026-11-27-155743.txt
$ ls backups
words-2026-11-27-155743.txt
$ cmp words.txt backups/words-*.txt && echo "kopia jest taka sama"
kopia jest taka sama

Na Twoim NAS-ie liczby albo data będą inne.

Ćwiczenie

Zatrzymaj program, gdy kopia już istnieje.