3 #include "command_db.h"
4 #include <stdlib.h> /* for malloc() */
5 #include <stdio.h> /* for FILE typedef, fopen(), fclose(), fgets() */
6 #include <stdint.h> /* for uint8_t */
7 #include <string.h> /* for strlen(), strtok() */
8 #include "main.h" /* for World struct */
9 #include "rexit.h" /* for exit_err() */
10 #include "misc.h" /* for textfile_sizes() */
14 /* Build string pointed to by "ch_ptr" from next token delimited by "delim",
15 * exit_err() with "err" as error message on malloc() failure.
17 static void copy_tokenized_string(struct World * world,
18 char ** ch_ptr, char * delim, char * err)
20 char * dsc_ptr = strtok(NULL, delim);
21 * ch_ptr = malloc(strlen(dsc_ptr) + 1);
22 exit_err(NULL == * ch_ptr, world, err);
23 memcpy(* ch_ptr, dsc_ptr, strlen(dsc_ptr) + 1);
28 extern char * get_command_longdsc(struct World * world, char * dsc_short)
30 struct Command * cmd_ptr = world->cmd_db->cmds;
33 if (0 == strcmp(dsc_short, cmd_ptr->dsc_short))
35 return cmd_ptr->dsc_long;
37 cmd_ptr = &cmd_ptr[1];
43 extern void init_command_db(struct World * world)
45 char * err = "Trouble in init_cmds() with fopen() on file 'commands'.";
46 FILE * file = fopen("config/commands", "r");
47 exit_err(NULL == file, world, err);
48 uint16_t lines, linemax;
49 textfile_sizes(file, &linemax, &lines);
50 err = "Trouble in init_cmds() with malloc().";
51 char * line = malloc(linemax);
52 exit_err(NULL == line, world, err);
53 struct Command * cmds = malloc(lines * sizeof(struct Command));
54 exit_err(NULL == line, world, err);
56 while (fgets(line, linemax, file))
58 cmds[i].id = atoi(strtok(line, " "));
59 copy_tokenized_string(world, &cmds[i].dsc_short, " ", err);
60 copy_tokenized_string(world, &cmds[i].dsc_long, "\n", err);
63 world->cmd_db = malloc(sizeof(struct CommandDB));
64 world->cmd_db->cmds = cmds;
65 world->cmd_db->n = lines;
66 err = "Trouble in init_cmds() with fclose() on file 'commands'.";
67 exit_err(fclose(file), world, err);
72 extern void free_command_db(struct World * world)
75 while (i < world->cmd_db->n)
77 free(world->cmd_db->cmds[i].dsc_short);
78 free(world->cmd_db->cmds[i].dsc_long);
81 free(world->cmd_db->cmds);