Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I concatenate two files into one?

Tags:

file

delphi

I have two binary files (suppose, this is a ZIP-file previously sliced into 2 parts). How do I can combine them into a single file? More precisely, add the second file to the first one.

UPDATE: Guys, thanks to everyone who responded me, but it's not exactly what I need. Basically, I need an analogue of the shell command: "copy /b file.000+file.001+file.002 file.bin"

like image 526
Red October Avatar asked Oct 24 '25 06:10

Red October


1 Answers

Like this:

var
  InStream, OutStream: TFileStream;
....
OutStream := TFileStream.Create(OutFileName, fmCreate);
try
  InStream := TFileStream.Create(InFileName1, fmOpenRead);
  try
    OutStream.CopyFrom(InStream, InStream.Size);
  finally
    InStream.Free;
  end;
  InStream := TFileStream.Create(InFileName2, fmOpenRead);
  try
    OutStream.CopyFrom(InStream, InStream.Size);
  finally
    InStream.Free;
  end;
finally
  OutStream.Free;
end;

Or more generally to concatenate multiple files:

procedure ConcatenateFiles(const InFileNames: array of string;
  const OutFileName: string);
var
  i: Integer;
  InStream, OutStream: TFileStream;
begin
  OutStream := TFileStream.Create(OutFileName, fmCreate);
  try
    for i := 0 to high(InFileNames) do
    begin
      InStream := TFileStream.Create(InFileNames[i], fmOpenRead);
      try
        OutStream.CopyFrom(InStream, InStream.Size);
      finally
        InStream.Free;
      end;
    end;
  finally
    OutStream.Free;
  end;
end;

Call it like this:

ConcatenateFiles(['Part1', 'Part2'], 'Outfile.zip')
like image 198
David Heffernan Avatar answered Oct 27 '25 00:10

David Heffernan