allow specifying file to extract
[btb/d2x.git] / utilities / hogextract.c
1 /*
2  * Written 1999 Jan 29 by Josh Cogliati
3  * I grant this program to public domain.
4  *
5  * Modified by Bradley Bell, 2002
6  * All modifications under GPL, version 2 or later
7  */
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <sys/types.h>
12 #include <sys/stat.h>
13 #include <fcntl.h>
14
15 int
16 main(int argc, char *argv[])
17 {
18         FILE *hogfile, *writefile;
19         int len;
20         char filename[13];
21         char *buf;
22         struct stat statbuf;
23         int v = 0;
24
25         if (argc > 1 && !strcmp(argv[1], "v")) {
26                 v = 1;
27                 argc--;
28                 argv++;
29         }
30
31         if (argc < 2) {
32                 printf("Usage: hogextract [v] hogfile [filename]\n"
33                        "extracts all the files in hogfile into the current directory\n"
34                            "Options:\n"
35                            "  v    View files, don't extract\n");
36                 exit(0);
37         }
38         hogfile = fopen(argv[1], "r");
39         stat(argv[1], &statbuf);
40         printf("%i\n", (int)statbuf.st_size);
41         buf = (char *)malloc(3);
42         fread(buf, 3, 1, hogfile);
43         printf("Extracting from: %s\n", argv[1]);
44         free(buf);
45         while(ftell(hogfile)<statbuf.st_size) {
46                 fread(filename, 13, 1, hogfile);
47                 fread(&len, sizeof(int), 1, hogfile);
48                 if (argc > 2 && strcmp(argv[2], filename))
49                         fseek(hogfile, len, SEEK_CUR);
50                 else {
51                         printf("Filename: %s \tLength: %i\n", filename, len);
52                         if (v)
53                                 fseek(hogfile, len, SEEK_CUR);
54                         else {
55                                 buf = (char *)malloc(len);
56                                 if (buf == NULL) {
57                                         printf("Unable to allocate memory\n");
58                                 } else {
59                                         fread(buf, len, 1, hogfile);
60                                         writefile = fopen(filename, "w");
61                                         fwrite(buf, len, 1, writefile);
62                                         fclose(writefile);
63                                         free(buf);
64                                 }
65                         }
66                 }
67         }
68         fclose(hogfile);
69
70         return 0;
71 }