standalone unpacker debug cosmetix
[libha.git] / src / main_unp.c
blob54fde3c991546b228d230f74327d23c941848e16
1 #include <fcntl.h>
2 #include <stdint.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <unistd.h>
8 #include <sys/stat.h>
9 #include <sys/types.h>
11 #include "libhaunp.h"
14 static int fdi = -1;
15 static int fdo = -1;
16 static int rdcur = 0, rdtotal = 0;
18 #ifndef _NDEBUG
19 # define OUTBUF_SIZE (1024*1024)
20 #else
21 # define OUTBUF_SIZE 1
22 #endif
23 static uint8_t *wrbuf;
26 static int bread (void *buf, int buf_len, void *udata) {
27 int res = read(fdi, buf, buf_len);
28 if (res >= 0) {
29 rdcur += res;
30 fprintf(stdout, "\r[%d/%d] %3d%%", rdcur, rdtotal, (int)((uint64_t)100*rdcur/rdtotal));
31 fflush(stdout);
33 return res;
37 int main (int argc, char *argv[]) {
38 haunp_t hup;
39 int res = 0;
40 #ifndef _NDEBUG
41 if (argc != 3) {
42 argc = 3;
43 argv[1] = "egatiles.dd2.haz";
44 argv[2] = "z01";
46 #endif
47 if (argc != 3) {
48 fprintf(stderr, "usage: %s infile outfile\n", argv[0]);
49 return 1;
51 fdi = open(argv[1], O_RDONLY|O_CLOEXEC);
52 if (fdi < 0) {
53 fprintf(stderr, "FATAL: can't open file: '%s'\n", argv[1]);
54 return 1;
56 fdo = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0640);
57 if (fdo < 0) {
58 fprintf(stderr, "FATAL: can't create file: '%s'\n", argv[2]);
59 return 1;
61 rdtotal = lseek(fdi, 0, SEEK_END);
62 lseek(fdi, 0, SEEK_SET);
63 hup = haunp_open_io(bread, NULL);
64 wrbuf = malloc(OUTBUF_SIZE);
65 for (;;) {
66 int rd = haunp_read(hup, wrbuf, sizeof(wrbuf));
67 if (rd <= 0) {
68 if (rd < 0) fprintf(stdout, "\nREAD ERROR!");
69 res = (rd < 0 ? -1 : 0);
70 break;
72 if (write(fdo, wrbuf, rd) != rd) {
73 fprintf(stdout, "\nWRITE ERROR!");
74 res = -1;
75 break;
78 free(wrbuf);
79 fprintf(stdout, "\n");
80 haunp_close(hup);
81 close(fdi);
82 close(fdo);
83 if (res != 0) unlink(argv[2]);
84 return res;