Skip to content

Instantly share code, notes, and snippets.

@mobius
Last active May 19, 2024 10:47
Show Gist options
  • Save mobius/1759816 to your computer and use it in GitHub Desktop.
Save mobius/1759816 to your computer and use it in GitHub Desktop.
using libzip to extract files
/* Copyright (C) 2011 rocenting#gmail.com */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/resource.h>
#include <dirent.h>
#include <limits.h>
#include <unistd.h>
#include <dirent.h>
#include <fcntl.h>
#include <limits.h>
#include <zip.h>
const char *prg;
static void safe_create_dir(const char *dir)
{
if (mkdir(dir, 0755) < 0) {
if (errno != EEXIST) {
perror(dir);
exit(1);
}
}
}
int main(int argc, char *argv[])
{
const char *archive;
struct zip *za;
struct zip_file *zf;
struct zip_stat sb;
char buf[100];
int err;
int i, len;
int fd;
long long sum;
prg = argv[0];
if (argc != 2) {
fprintf(stderr, "usage: %s archive\n", prg);
return 1;
}
archive = argv[1];
if ((za = zip_open(archive, 0, &err)) == NULL) {
zip_error_to_str(buf, sizeof(buf), err, errno);
fprintf(stderr, "%s: can't open zip archive `%s': %s/n", prg,
archive, buf);
return 1;
}
for (i = 0; i < zip_get_num_entries(za, 0); i++) {
if (zip_stat_index(za, i, 0, &sb) == 0) {
printf("==================/n");
len = strlen(sb.name);
printf("Name: [%s], ", sb.name);
printf("Size: [%llu], ", sb.size);
printf("mtime: [%u]/n", (unsigned int)sb.mtime);
if (sb.name[len - 1] == '/') {
safe_create_dir(sb.name);
} else {
zf = zip_fopen_index(za, i, 0);
if (!zf) {
fprintf(stderr, "boese, boese/n");
exit(100);
}
fd = open(sb.name, O_RDWR | O_TRUNC | O_CREAT, 0644);
if (fd < 0) {
fprintf(stderr, "boese, boese/n");
exit(101);
}
sum = 0;
while (sum != sb.size) {
len = zip_fread(zf, buf, 100);
if (len < 0) {
fprintf(stderr, "boese, boese/n");
exit(102);
}
write(fd, buf, len);
sum += len;
}
close(fd);
zip_fclose(zf);
}
} else {
printf("File[%s] Line[%d]/n", __FILE__, __LINE__);
}
}
if (zip_close(za) == -1) {
fprintf(stderr, "%s: can't close zip archive `%s'/n", prg, archive);
return 1;
}
return 0;
}
@richdrich
Copy link

What C environment uses "/n" rather than "\n"

@BCDeshiG
Copy link

BCDeshiG commented Nov 5, 2021

Ouch the duplicate includes.
Also hello Google Search.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment