Use safe temporary files
[jumpnbump.git] / modify / jnbunpack.c
blobaa55d79d85c1796373e2fa313bb333fc14c3963e
1 /*
2 * unpack.c
3 * Copyright (C) 1998 Brainchild Design - http://brainchilddesign.com/
4 *
5 * Copyright (C) 2001 "timecop" <timecop@japan.co.jp>
7 * Copyright (C) 2002 Florian Schulze <crow@icculus.org>
9 * This file is part of Jump'n'Bump.
11 * Jump'n'Bump is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * Jump'n'Bump is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 #include <errno.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <fcntl.h>
30 #include <string.h>
31 #include <sys/types.h>
32 #ifndef _MSC_VER
33 #include <unistd.h>
34 #else
35 #include <io.h>
36 #endif
38 typedef struct {
39 char filename[12];
40 unsigned int offset;
41 unsigned int size;
42 } DirEntry;
44 #ifndef O_BINARY
45 #define O_BINARY 0
46 #endif
48 int main(int argc, char **argv)
50 int fd;
51 DirEntry *datafile;
52 int num_entries, i;
54 if (argc < 2) {
55 printf("dumbass, specify filename to unpack\n");
56 exit(1);
59 fd = open(argv[1], O_RDONLY | O_BINARY);
60 if (fd == -1) {
61 perror("open datafile");
62 exit(1);
64 /* get number of entries */
65 read(fd, &num_entries, 4);
67 printf("%d entries in datafile\n", num_entries);
69 datafile = calloc(num_entries, sizeof(DirEntry));
70 read(fd, datafile, num_entries * sizeof(DirEntry));
71 printf("Directory Listing:\n");
72 for (i = 0; i < num_entries; i++) {
73 char filename[14];
74 memset(filename, 0, sizeof(filename));
75 strncpy(filename, datafile[i].filename, 12);
76 printf("%02d:\t%s (%u bytes)\n", i, filename,
77 datafile[i].size);
80 for (i = 0; i < num_entries; i++) {
81 int outfd;
82 char filename[14];
83 char *buf;
84 memset(filename, 0, sizeof(filename));
85 strncpy(filename, datafile[i].filename, 12);
86 printf("Extracting %s ", filename);
87 fflush(stdout);
89 if (unlink(filename) == -1 && errno != ENOENT) {
90 perror("cannot unlink file");
91 exit(1);
93 outfd = open(filename, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0644);
94 if (!outfd) {
95 perror("cant open file");
96 exit(1);
98 lseek(fd, datafile[i].offset, SEEK_SET);
99 buf = calloc(1, datafile[i].size + 16);
100 read(fd, buf, datafile[i].size);
101 write(outfd, buf, datafile[i].size);
102 close(outfd);
103 free(buf);
104 printf("OK\n");
106 close(fd);
107 return 0;