Advertisement
Guest User

Unpack tar with D and libarchive

a guest
Nov 12th, 2015
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.19 KB | None | 0 0
  1. module main;
  2.  
  3. import std.stdio;
  4. import std.string;
  5. import std.conv;
  6. import std.file;
  7. import std.c.stdlib;
  8.  
  9. import libarchive.all;
  10.  
  11. void main(string[] args)
  12. {
  13.     if (args.length < 2)
  14.     {
  15.         writefln("Usage:\n%s filename.tar", args[0]);
  16.         return;
  17.     }
  18.    
  19.     string filename = args[1];
  20.  
  21.     archive* a = archive_read_new();
  22.     archive_read_support_format_tar(a);
  23.     int r = archive_read_open_filename(a, cast(char*)toStringz(filename), 10240);
  24.    
  25.     archive_entry* entry;
  26.     while (archive_read_next_header(a, &entry) == ARCHIVE_OK)
  27.     {
  28.         char* n = archive_entry_pathname(entry);
  29.         string path = to!string(n);
  30.                
  31.         if (archive_entry_filetype(entry) == AE_IFDIR)
  32.         {
  33.             if (!exists(path))
  34.                 mkdir(path);
  35.         }
  36.         else
  37.         {
  38.             size_t size = cast(size_t)archive_entry_size(entry);
  39.             if (size > 0)
  40.             {
  41.                 void* fileContents = malloc(size);
  42.                 archive_read_data_into_buffer(a, fileContents, size);
  43.                 std.file.write(path, fileContents[0..size]);
  44.                 free(fileContents);
  45.             }
  46.         }
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement