summaryrefslogtreecommitdiff
path: root/packassets.c
blob: 5b31b0df291525972b3cbfcf0400441ec7535453 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include "error.h"

#include <stdio.h>
#include <string.h>

#define buffer_size 256
#define filename "pack"

typedef struct {
	int size;
	int offset;
	char name[56];
} Entry;

int main(int argc, char** argv) {
	int i, j, file_count, blob_offset, read, head_size;
	char buffer[buffer_size];
	char name[56];
	const char* workingdir, * dsep = "";
	Entry entry;
	FILE* outfile, * infile;

	outfile = fopen(filename, "wb");
	if (!outfile) {
		fprintf(
			stderr,
			"Failed to open '%s' for writing.\n",
			filename
		);
		return error_file_not_found;
	}

	file_count = argc - 2;
	head_size = 8;
	blob_offset = head_size + file_count * sizeof entry;
	workingdir = argv[1];
	if (workingdir[strlen(workingdir) - 1] != '/')
		dsep = "/";

	fwrite(&file_count,  4, 1, outfile);
	fwrite(&blob_offset, 4, 1, outfile);

	entry.offset = blob_offset;

	for (i = 0; i < file_count; i++) {
		strcpy(entry.name, argv[i + 2]);
		strcpy(name, workingdir);
		strcat(name, dsep);
		strcat(name, entry.name);

		infile = fopen(name, "rb");
		if (!infile) {
			fprintf(
				stderr,
				"Failed to open '%s' for reading.\n",
				entry.name
			);
			return error_file_not_found;
		}

		fseek(infile, 0, SEEK_END);
		entry.size = ftell(infile);
		rewind(infile);

		fseek(outfile, head_size + i * sizeof entry, SEEK_SET);
		fwrite(&entry, 1, sizeof entry, outfile);

		fseek(outfile, entry.offset, SEEK_SET);
		for (j = 0; j < entry.size; j += buffer_size) {
			read = fread(buffer, 1, buffer_size, infile);
			fwrite(buffer, 1, read, outfile);
		}

		entry.offset += entry.size;

		fclose(infile);
	}

	fclose(outfile);

	return error_none;
}