Delphi fast file copy

后端 未结 6 1953
小鲜肉
小鲜肉 2020-12-12 18:17

I\'m writing an app that supposed to copy a bunch of files from one place to another. When I\'m using TFileStream for the copy it is 3-4 times slower than copying the files

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-12 19:06

    Or you can do it the "dirty" way ... I have found some old code that does the job (not sure if it is fast):

    procedure CopyFile(const FileName, DestName: string);
    var
       CopyBuffer   : Pointer; { buffer for copying }
       BytesCopied  : Longint;
       Source, Dest : Integer; { handles }
       Destination  : TFileName; { holder for expanded destination name }
    
    const
         ChunkSize  : Longint = 8192; { copy in 8K chunks }
    
    begin
         Destination := DestName;
         GetMem(CopyBuffer, ChunkSize); { allocate the buffer }
         try
           Source := FileOpen(FileName, fmShareDenyWrite); { open source file }
           if Source < 0
              then raise EFOpenError.CreateFmt('Error: Can''t open file!', [FileName]);
           try
             Dest := FileCreate(Destination); { create output file; overwrite existing }
             if Dest < 0
                then raise EFCreateError.CreateFmt('Error: Can''t create file!', [Destination]);
             try
               repeat
                 BytesCopied := FileRead(Source, CopyBuffer^, ChunkSize); { read chunk }
                 if BytesCopied > 0  {if we read anything... }
                    then FileWrite(Dest, CopyBuffer^, BytesCopied); { ...write chunk }
               until BytesCopied < ChunkSize; { until we run out of chunks }
    
             finally
               FileClose(Dest); { close the destination file }
             end;
    
           finally
             FileClose(Source); { close the source file }
           end;
    
         finally
           FreeMem(CopyBuffer, ChunkSize); { free the buffer }
         end;
    end;
    

提交回复
热议问题