8 #include <readline/readline.h>
10 /* the last 32 bits are a version number to be increased on breaking changes.
12 static const char magic[]
13 = { 0, 0, 0, 0, 'T', 'E', 'X', 'T', 'A', 'D', 'V', 0, 0, 0, 0 };
15 #define MLEN sizeof(magic)
17 /* Every object is serialized in a buffer with the following format:
19 * | offset | location | weight | capacity | health |
21 * with each field 32 bits long, for a total of 160 bytes. Each field is a
22 * SIGNED 32 bit integer. The meaning of the fields is as follows:
24 * - offset : the current object, that is objs[offset]
25 * - location : the offset of the location, if NULL -1
26 * - weight, capacity, health : the propriety of the object.
28 * This should make cheating a little bit harder.
38 line = readline("Save to file: ");
39 if (!line || !*line) {
40 printf("Invalid filename\n");
48 /* b = binary mode, for windows compatibility I guess */
49 if ((f = fopen(line, "wb")) == NULL) {
50 printf("Cannot write file!\n");
54 /* write magic header */
55 fwrite(magic, 1, MLEN, f);
57 /* write the objects */
58 for (obj = objs; obj < obj_end; ++obj) {
59 int32_t offset, location, weight, capacity, health;
62 if (obj->location == NULL)
65 location = obj->location - objs;
67 capacity = obj->capacity;
70 printf("saved: %d %d %d %d %d\n", offset, location, weight,
73 fwrite(&offset, 4, 1, f);
74 fwrite(&location, 4, 1, f);
75 fwrite(&weight, 4, 1, f);
76 fwrite(&capacity, 4, 1, f);
77 fwrite(&health, 4, 1, f);
92 line = readline("Load from file: ");
93 if (!line || !*line) {
94 printf("Invalid filename\n");
102 if ((f = fopen(line, "rb")) == NULL) {
103 printf("Cannot open file %s\n", line);
109 fread(m, MLEN, 1, f);
110 if (memcmp(m, magic, MLEN)) {
111 printf("Wrong magic in file, cannot load.\n");
115 /* read all the objects */
117 int32_t offset, location, weight, capacity, health;
119 if ((r = fread(&offset, 1, 4, f)) != 4)
121 if ((r = fread(&location, 1, 4, f)) != 4)
123 if ((r = fread(&weight, 1, 4, f)) != 4)
125 if ((r = fread(&capacity, 1, 4, f)) != 4)
127 if ((r = fread(&health, 1, 4, f)) != 4)
130 if (objs + offset >= obj_end)
134 objs[offset].location = NULL;
136 if (objs + location >= obj_end)
139 objs[offset].location = objs + location;
142 objs[offset].weight = weight;
143 objs[offset].capacity = capacity;
144 objs[offset].health = health;
158 printf("Error in loading file!\n");