Mega Code Archive

 
Categories / Delphi / Examples
 

Copyfile

There is no quick and easy CopyFile routine shipped with Delphi. So you have to cross the i's and dot the t's yourself. This ways is as good as any although a STREAM might also be used instead of a buffer (by using two TFileStream streams, and 'create'ing the first by associating it with source file, then 'copying' this stream to a second stream, which is then 'CopyToFile'd)... Note that the srcFName and destFName parameters should be FILENAMES INCLUDING FULL PATH NAMES. -These will have been acquired elsewhere, obviously. Note that src file is opened using ReSet and dest file is opened using ReWrite, and if dest file already exists it will be overwritten... function TInstallForm.CopyFileUsingBuffer(srcFName, destFName: String): Boolean; type {define a buffer as a character array type of length maxBufferSize...} TMyBufferArray = array[1..maxBufferSize] of char; {and define a pointer type to point into the buffer...} TMyBuffer = ^TMyBufferArray; var buffer: TMyBuffer; srcFile, destFile: File; bytesRead, bytesWritten, i: LongInt; readOrWriteError: Boolean; begin bytesRead := 0; try {to allocate memory for the buffer...} getmem(buffer, maxBufferSize); AssignFile(srcFile, srcFName); AssignFile(destFile, destFName); try {to open both source and destination files...} reSet(srcFile, 1); reWrite(destFile, 1); try repeat {put source file data into into the buffer and write buffer to destination file...} blockRead(srcFile, buffer^, sizeof(buffer^), bytesRead); blockWrite(destFile, buffer^, bytesRead, bytesWritten); until ((bytesRead < maxBufferSize) or (bytesRead = 0) or (bytesWritten <> bytesRead)); finally closefile(srcFile); closeFile(destFile); end; {putting source file data into memory} except on E: EInOutError do begin {you COULD call some kind of GetError routine here to retrieve the exact error code if you wanted to...} readOrWriteError := True; end end; {trying to open source file} finally freemem(buffer, maxBufferSize); end; if (readOrWriteError = True) then Result := True; if (readOrWriteError = False) then Result := False; end;