comparison lwar/add.c @ 172:47427342e41d

lwar now creates, lists, and adds to archive files
author lost
date Sun, 01 Mar 2009 22:59:52 +0000
parents
children cc41ccee8f64
comparison
equal deleted inserted replaced
171:d610b8aef91b 172:47427342e41d
1 /*
2 add.c
3 Copyright © 2009 William Astle
4
5 This file is part of LWAR.
6
7 LWAR is free software: you can redistribute it and/or modify it under the
8 terms of the GNU General Public License as published by the Free Software
9 Foundation, either version 3 of the License, or (at your option) any later
10 version.
11
12 This program is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 more details.
16
17 You should have received a copy of the GNU General Public License along with
18 this program. If not, see <http://www.gnu.org/licenses/>.
19
20
21 Implements the program startup code
22
23 */
24
25 #ifdef HAVE_CONFIG_H
26 #include "config.h"
27 #endif
28
29 #include <errno.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32
33 #include "lwar.h"
34
35 void do_add(void)
36 {
37 FILE *f;
38 unsigned char buf[8];
39 long l;
40 int c;
41 FILE *f2;
42 int i;
43
44 f = fopen(archive_file, "r+");
45 if (!f)
46 {
47 if (errno == ENOENT)
48 {
49 f = fopen(archive_file, "w");
50 if (f)
51 {
52 fputs("LWAR1V", f);
53 goto doadd;
54 }
55 }
56 perror("Cannot open archive file");
57 }
58
59 fread(buf, 1, 6, f);
60 if (memcmp("LWAR1V", buf, 6))
61 {
62 fprintf(stderr, "%s is not a valid archive file.\n", archive_file);
63 exit(1);
64 }
65
66 for (;;)
67 {
68 c = fgetc(f);
69 if (c == EOF && ferror(f))
70 {
71 perror("Reading archive file");
72 exit(1);
73 }
74 if (c == EOF)
75 goto doadd;
76
77 if (!c)
78 {
79 fseek(f, -1, SEEK_CUR);
80 goto doadd;
81 }
82
83 // find the end of the file name
84 while (c)
85 {
86 c = fgetc(f);
87 if (c == EOF || ferror(f))
88 {
89 fprintf(stderr, "Bad archive file\n");
90 exit(1);
91 }
92 }
93
94 // get length of archive member
95 l = 0;
96 c = fgetc(f);
97 l = c << 24;
98 c = fgetc(f);
99 l |= c << 16;
100 c = fgetc(f);
101 l |= c << 8;
102 c = fgetc(f);
103 l |= c;
104
105 fseek(f, l, SEEK_CUR);
106 }
107 // back up to the NUL byte at the end of the file
108 fseek(f, -1, SEEK_CUR);
109 doadd:
110 for (i = 0; i < nfiles; i++)
111 {
112 f2 = fopen(files[i], "r");
113 if (!f2)
114 {
115 fprintf(stderr, "Cannot open file %s:", files[i]);
116 perror("");
117 exit(1);
118 }
119 fseek(f2, 0, SEEK_END);
120 l = ftell(f2);
121 fseek(f2, 0, SEEK_SET);
122 fputs(files[i], f);
123 fputc(0, f);
124 fputc(l >> 24, f);
125 fputc((l >> 16) & 0xff, f);
126 fputc((l >> 8) & 0xff, f);
127 fputc(l & 0xff, f);
128 while (l)
129 {
130 c = fgetc(f2);
131 fputc(c, f);
132 l--;
133 }
134 }
135
136 // flag end of file
137 fputc(0, f);
138 }