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 = "Trouble in init_cmds() with fopen() on file 'commands'.";
81 FILE * file = fopen("config/commands", "r");
82 exit_err(NULL == file, world, err);
83 uint16_t lines, linemax;
84 textfile_sizes(file, &linemax, &lines);
85 err = "Trouble in init_cmds() with malloc().";
86 char * line = malloc(linemax);
87 exit_err(NULL == line, world, err);
88 struct Command * cmds = malloc(lines * sizeof(struct Command));
89 exit_err(NULL == line, world, err);
91 while (fgets(line, linemax, file))
93 cmds[i].id = atoi(strtok(line, " "));
94 copy_tokenized_string(world, &cmds[i].dsc_short, " ", err);
95 copy_tokenized_string(world, &cmds[i].dsc_long, "\n", err);
99 world->cmd_db = malloc(sizeof(struct CommandDB));
100 world->cmd_db->cmds = cmds;
101 world->cmd_db->n = lines;
102 err = "Trouble in init_cmds() with fclose() on file 'commands'.";
103 exit_err(fclose(file), world, err);
108 extern void free_command_db(struct World * world)
111 while (i < world->cmd_db->n)
113 free(world->cmd_db->cmds[i].dsc_short);
114 free(world->cmd_db->cmds[i].dsc_long);
117 free(world->cmd_db->cmds);