2 * Copyright (c) 2011 Josef 'Jeff' Sipek
10 typedef unsigned char u8
;
33 static void storeoct(u8
*buf
, int len
, unsigned val
)
38 buf
[len
] = '0' + (val
% 8);
44 static void mkhdr(struct cpio_hdr
*hdr
, char *fn
, unsigned filesize
)
46 memset(hdr
, '0', sizeof(struct cpio_hdr
));
54 storeoct(hdr
->namesize
, 6, strlen(fn
)+1);
55 storeoct(hdr
->filesize
, 11, filesize
);
58 static unsigned __text(char *fn
, int lrecl
)
61 struct buffer
*first
, *last
, *cur
, *tmp
;
67 fprintf(stderr
, "Error: zero lrecl is bogus\n");
73 fprintf(stderr
, "Error: could not open file '%s'\n",
82 cur
= malloc(sizeof(struct buffer
) + lrecl
+ 1);
84 fprintf(stderr
, "Error: OOM\n");
88 if (!fgets((char*)cur
->data
, lrecl
+1, f
))
91 l
= strlen((char*)cur
->data
);
93 if (l
&& cur
->data
[l
-1])
98 memset(cur
->data
+l
, ' ', lrecl
-l
);
112 mkhdr(&hdr
, basename(fn
), flen
);
113 fwrite(&hdr
, sizeof(hdr
), 1, stdout
);
114 fwrite(basename(fn
), strlen(basename(fn
))+1, 1, stdout
);
116 for(cur
=first
; cur
; cur
=tmp
) {
117 fwrite(cur
->data
, 1, lrecl
, stdout
);
122 return flen
+ strlen(basename(fn
)) + 1 + sizeof(hdr
);
126 static unsigned __bin(char *fn
)
129 struct buffer
*first
, *last
, *cur
, *tmp
;
136 fprintf(stderr
, "Error: could not open file '%s'\n",
145 cur
= malloc(sizeof(struct buffer
) + BUF_LEN
);
147 fprintf(stderr
, "Error: OOM\n");
151 memset(cur
->data
, 0, BUF_LEN
);
152 if (!(s
= fread(cur
->data
, 1, BUF_LEN
, f
)))
168 mkhdr(&hdr
, basename(fn
), flen
);
169 fwrite(&hdr
, sizeof(hdr
), 1, stdout
);
170 fwrite(basename(fn
), strlen(basename(fn
))+1, 1, stdout
);
172 for(cur
=first
; cur
; cur
=tmp
) {
173 fwrite(cur
->data
, 1, cur
->len
, stdout
);
178 return flen
+ strlen(basename(fn
)) + 1 + sizeof(hdr
);
181 static void mktail(unsigned len
)
185 mkhdr(&hdr
, "TRAILER!!!", 0);
186 fwrite(&hdr
, sizeof(hdr
), 1, stdout
);
187 printf("TRAILER!!!");
190 fwrite("", 1, 1, stdout
); // write a nul char
195 int main(int argc
, char **argv
)
204 while((i
+1) < argc
) {
208 if (!strcmp(argv
[i
], "text")) {
209 lrecl
= atoi(argv
[i
+1]);
212 len
+= __text(fn
, lrecl
);
213 } else if (!strcmp(argv
[i
], "bin")) {
217 fprintf(stderr
, "Error: cannot understand type '%s'\n",