Search code examples
pascalfreepascal

FreePascal - How can I copy a file from one location and paste it in another?


I am attempting to get a program to paste a copy of itself in the windows start-up folder. I have only been able to find the Lazarus function included in FileUtils, CopyFile() but as I'm not using Lazarus this solution doesn't work for me. is there any other way that I can do this in FreePascal? all other things related to files that I can find for FreePascal are referring to text files or the File type.


Solution

  • You may copy one file to another with the oldschool File type and routines:

    function CopyFile(const SrcFileName, DstFileName: AnsiString): Boolean;
    var
      Src, Dst: File;
      Buf: array of Byte;
      ReadBytes: Int64;
    begin
      Assign(Src, SrcFileName);
    {$PUSH}{$I-}
      Reset(Src, 1);
    {$POP}
      if IOResult <> 0 then
        Exit(False);
    
      Assign(Dst, DstFileName);
    {$PUSH}{$I-}
      Rewrite(Dst, 1);
    {$POP}
      if IOResult <> 0 then begin
        Close(Src);
        Exit(False);
      end;
    
      SetLength(Buf, 64 * 1024 * 1024);
      while not Eof(Src) do begin
    {$PUSH}{$I-}
        BlockRead(Src, Buf[0], Length(Buf), ReadBytes);
    {$POP}
        if IOResult <> 0 then begin
          Close(Src);
          Close(Dst);
          Exit(False);
        end;
    
    {$PUSH}{$I-}
        BlockWrite(Dst, Buf[0], ReadBytes);
    {$POP}
        if IOResult <> 0 then begin
          Close(Src);
          Close(Dst);
          Exit(False);
        end;
      end;
    
      Close(Src);
      Close(Dst);
      Exit(True);
    end;
    
    begin
      if not CopyFile('a.txt', 'b.txt') then
        Halt(1);
    end.