1 /* src/client/command_db.c */
3 #include "command_db.h"
4 #include <stdint.h> /* uint8_t, uint32_t */
5 #include <stdio.h> /* FILE */
6 #include <stdlib.h> /* free() */
7 #include <string.h> /* memcpy(), strlen(), strtok(), strcmp() */
8 #include "../common/readwrite.h" /* try_fopen(), try_fclose(), try_fgets()
11 #include "../common/rexit.h" /* for exit_err() */
12 #include "../common/try_malloc.h" /* try_malloc() */
13 #include "cleanup.h" /* set_cleanup_flag() */
14 #include "world.h" /* global world */
18 /* Point "ch_ptr" to next strtok() string in "line" delimited by "delim".*/
19 static void copy_tokenized_string(char * line, char ** ch_ptr, char * delim);
23 static void copy_tokenized_string(char * line, char ** ch_ptr, char * delim)
25 char * f_name = "copy_tokenized_string()";
26 char * dsc_ptr = strtok(line, delim);
27 * ch_ptr = try_malloc(strlen(dsc_ptr) + 1, f_name);
28 memcpy(* ch_ptr, dsc_ptr, strlen(dsc_ptr) + 1);
33 extern struct Command * get_command_data(char * dsc_short)
35 struct Command * cmd_ptr = world.cmd_db.cmds;
37 while (i < world.cmd_db.n)
39 if (0 == strcmp(dsc_short, cmd_ptr->dsc_short))
43 cmd_ptr = &cmd_ptr[1];
46 char * err_start = "get_command_data() failed on request for: ";
47 char err[strlen(err_start) + strlen(dsc_short) + 1];
48 sprintf(err, "%s%s", err_start, dsc_short);
49 exit_err(i == world.cmd_db.n, err);
55 extern void init_command_db()
57 char * f_name = "init_command_db()";
58 char * path = "confclient/commands";
59 FILE * file = try_fopen(path, "r", f_name);
61 uint32_t linemax = textfile_sizes(file, &lines);
62 char line[linemax + 1];
63 world.cmd_db.cmds = try_malloc(lines * sizeof(struct Command), f_name);
66 while (try_fgets(line, linemax + 1, file, f_name))
68 if ('\n' == line[0] || 0 == line[0])
72 copy_tokenized_string(line, &world.cmd_db.cmds[i].dsc_short, delim);
73 copy_tokenized_string(NULL, &world.cmd_db.cmds[i].server_msg, delim);
74 if (!strcmp("0", world.cmd_db.cmds[i].server_msg))
76 free(world.cmd_db.cmds[i].server_msg);
77 world.cmd_db.cmds[i].server_msg = NULL;
79 char * arg_string = strtok(NULL, delim);
80 world.cmd_db.cmds[i].arg = arg_string[0];
81 copy_tokenized_string(NULL, &world.cmd_db.cmds[i].dsc_long, "\n");
84 try_fclose(file, f_name);
85 world.cmd_db.n = lines;
86 set_cleanup_flag(CLEANUP_COMMANDS);
91 extern void free_command_db()
94 while (i < world.cmd_db.n)
96 free(world.cmd_db.cmds[i].dsc_short);
97 free(world.cmd_db.cmds[i].dsc_long);
98 free(world.cmd_db.cmds[i].server_msg);
101 free(world.cmd_db.cmds);