2009. október 6., kedd

How to split and join a file using TFileStream


Problem/Question/Abstract:

How to split and join a file using TFileStream

Answer:

{Procedure Splitfile
Parameters:
sourcefilename: name of file to split
blocksize: maximum size of the parts to create

Call method:
static

Description:

Will split the passed file into partial files with a size of blocksize bytes (the last one may be smaller). The names of the files are created from the sourcefilename by replacing the extension with a number, .000, .001 etc. The files can be concatenated using the DOS Copy command with the /b switch to regenerate the original file.

Error Conditions:
I/O errors will raise exceptions.

Created: 03.03.98 by P. Below}

procedure Splitfile(const sourcefilename: string; blocksize: Longint);
var
  targetfilename: string;
  filecounter: Integer;
  bytesRemaining, bytesToWrite: LongInt;
  source, target: TFileStream;
begin
  if not FileExists(sourcefilename) or (blocksize < = 0) then
    Exit;
  source := TFileStream.Create(sourcefilename, fmOpenRead or fmShareDenyNone);
  try
    filecounter := 0;
    bytesRemaining := source.Size;
    while bytesRemaining > 0 do
    begin
      targetfilename := ChangeFileExt(sourcefilename, Format('.%.3d', [filecounter]));
      if blocksize < bytesRemaining then
        bytesToWrite := blocksize
      else
        bytesToWrite := bytesRemaining;
      target := TFileStream.Create(targetfilename, fmCreate);
      try
        target.CopyFrom(source, bytesToWrite);
        bytesRemaining := bytesRemaining - bytesToWrite;
        Inc(filecounter);
      finally
        target.Free;
      end;
    end;
  finally
    source.Free;
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése