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 uint8_t is_command_id_shortdsc(struct World * world,
29 uint8_t id, char * shortdsc)
31 struct Command * cmd_ptr = world->cmd_db->cmds;
34 if (id == cmd_ptr->id)
36 if (strcmp(shortdsc, cmd_ptr->dsc_short))
42 cmd_ptr = &cmd_ptr[1];
48 extern uint8_t get_command_id(struct World * world, char * dsc_short)
50 struct Command * cmd_ptr = world->cmd_db->cmds;
53 if (0 == strcmp(dsc_short, cmd_ptr->dsc_short))
57 cmd_ptr = &cmd_ptr[1];
63 extern char * get_command_longdsc(struct World * world, char * dsc_short)
65 struct Command * cmd_ptr = world->cmd_db->cmds;
68 if (0 == strcmp(dsc_short, cmd_ptr->dsc_short))
70 return cmd_ptr->dsc_long;
72 cmd_ptr = &cmd_ptr[1];
78 extern void init_command_db(struct World * world)
80 char * err_o = "Trouble in init_cmds() with fopen() on file 'commands'.";
81 char * err_s = "Trouble in init_cmds() with textfile_sizes().";
82 char * err_m = "Trouble in init_cmds() with malloc().";
83 char * err_c = "Trouble in init_cmds() with fclose() on file 'commands'.";
85 char * path = "config/commands";
86 FILE * file = fopen(path, "r");
87 exit_err(NULL == file, world, err_o);
88 uint16_t lines, linemax;
89 exit_err(textfile_sizes(file, &linemax, &lines), world, err_s);
92 struct Command * cmds = malloc(lines * sizeof(struct Command));
93 exit_err(NULL == line, world, err_m);
95 while (fgets(line, linemax, file))
97 cmds[i].id = atoi(strtok(line, " "));
98 copy_tokenized_string(world, &cmds[i].dsc_short, " ", err_m);
99 copy_tokenized_string(world, &cmds[i].dsc_long, "\n", err_m);
102 exit_err(fclose(file), world, err_c);
104 world->cmd_db = malloc(sizeof(struct CommandDB));
105 world->cmd_db->cmds = cmds;
106 world->cmd_db->n = lines;
111 extern void free_command_db(struct World * world)
114 while (i < world->cmd_db->n)
116 free(world->cmd_db->cmds[i].dsc_short);
117 free(world->cmd_db->cmds[i].dsc_long);
120 free(world->cmd_db->cmds);