pasbunzip2.pas 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. program pasbunzip2;
  2. {
  3. This file is part of the Free Pascal packages.
  4. Copyright (c) 2012 Reinier Olislagers
  5. Tests bzip2 decompression.
  6. See the file COPYING.FPC, included in this distribution,
  7. for details about the copyright.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  11. **********************************************************************}
  12. {$mode objfpc}{$H+}
  13. {
  14. Example .bz2 file extractor.
  15. Decompresses a .bz2 file into another file using the classes-based bzip2stream unit
  16. Usage: bunzip2 compressedfile.bz2
  17. }
  18. uses classes, bzip2stream;
  19. function Decompress(SourceFile, TargetFile: string): boolean;
  20. var
  21. InFile:TFileStream;
  22. Decompressed:TDecompressBzip2Stream;
  23. OutFile:TFileStream;
  24. Buffer: Pointer;
  25. i: integer;
  26. const buffersize=$2000;
  27. begin
  28. result:=false; //fail by default
  29. InFile:=TFileStream.Create(SourceFile, fmOpenRead);
  30. try
  31. try
  32. Decompressed:=TDecompressBzip2Stream.Create(InFile);
  33. except
  34. // So[5mething went wrong, e.g. invalid format
  35. // Now get out of function with result false
  36. exit;
  37. end;
  38. OutFile:=TFileStream.Create(TargetFile, fmCreate);
  39. try
  40. //We don't have seek on the TDecompressBzip2stream, so can't use
  41. //CopyFrom...
  42. //Decompressed.CopyFrom(InFile, InFile.Size);
  43. GetMem(Buffer,BufferSize);
  44. repeat
  45. i:=Decompressed.Read(buffer^,BufferSize);
  46. if i>0 then
  47. OutFile.WriteBuffer(buffer^,i);
  48. until i<BufferSize;
  49. result:=true;
  50. finally
  51. Decompressed.Free;
  52. OutFile.Free;
  53. end;
  54. finally
  55. InFile.Free;
  56. end;
  57. end;
  58. var
  59. CompressedFile:string;
  60. DecompressedFile:string;
  61. begin
  62. CompressedFile:=ParamStr(1);
  63. if CompressedFile='' then
  64. begin
  65. writeln('Usage: '+ParamStr(0)+' <file>');
  66. halt(13); // show error in exit code
  67. end;
  68. DecompressedFile:=CompressedFile+'.out';
  69. if Decompress(CompressedFile, DecompressedFile) then
  70. begin
  71. writeln('Decompressed '+CompressedFile+' to '+DecompressedFile);
  72. end
  73. else
  74. begin
  75. writeln('An error occurred while decompressing '+CompressedFile);
  76. halt(1); // show error in exit code
  77. end;
  78. end.