[RE] Need a small tar file extraction example
PratikGajera opened this issue · 1 comments
Hi,
Library is so nice. I want to integrate it in my application.
Do you have any small example to extract tar file in my current directory?
Thanks,
PG
int untar_file_to(const char *tar_name, const char dest_path) {
mtar_t tar;
/ Open archive for reading */
int ret = mtar_open(&tar, tar_name, "r");
if (MTAR_ESUCCESS != ret) {
return ret;
}
mtar_header_t h;
while ((mtar_read_header(&tar, &h)) != MTAR_ENULLRECORD) {
printf("%s (%d bytes)\n", h.name, h.size);
char dest_file[512] = {};
snprintf(dest_file, sizeof(dest_file) / sizeof(char), "%s/%s", dest_path, h.name);
if ('/' == h.name[strlen(h.name) - 1]) {
mkdir(dest_file, 0777);
mtar_next(&tar);
continue;
}
FILE *f = fopen(dest_file, "w");
if (!f) {
return MTAR_EOPENFAIL;
}
char p;
p = calloc(1, h.size + 1);
if (MTAR_ESUCCESS != mtar_read_data(&tar, p, h.size)) {
free(p);
fclose(f);
mtar_close(&tar);
return MTAR_EREADFAIL;
}
fwrite(p, 1, h.size, f);
free(p);
fclose(f);
mtar_next(&tar);
}
/ Close archive */
mtar_close(&tar);
return 0;
}