1 /* src/client/command_db.c */
3 #include "command_db.h"
4 #include <stddef.h> /* NULL */
5 #include <stdint.h> /* uint8_t, uint32_t */
6 #include <stdio.h> /* FILE */
7 #include <stdlib.h> /* free() */
8 #include <string.h> /* memcpy(), strlen(), strtok(), strcmp() */
9 #include "../common/readwrite.h" /* try_fopen(), try_fclose(), try_fgets()
12 #include "../common/rexit.h" /* for exit_err() */
13 #include "../common/try_malloc.h" /* try_malloc() */
14 #include "cleanup.h" /* set_cleanup_flag() */
15 #include "world.h" /* global world */
19 /* Point "ch_ptr" to next strtok() string in "line" delimited by "delim".*/
20 static void copy_tokenized_string(char * line, char ** ch_ptr, char * delim);
24 static void copy_tokenized_string(char * line, char ** ch_ptr, char * delim)
26 char * f_name = "copy_tokenized_string()";
27 char * dsc_ptr = strtok(line, delim);
28 * ch_ptr = try_malloc(strlen(dsc_ptr) + 1, f_name);
29 memcpy(* ch_ptr, dsc_ptr, strlen(dsc_ptr) + 1);
34 extern struct Command * get_command(char * dsc_short)
36 struct Command * cmd_ptr = world.cmd_db.cmds;
38 while (i < world.cmd_db.n)
40 if (0 == strcmp(dsc_short, cmd_ptr->dsc_short))
44 cmd_ptr = &cmd_ptr[1];
47 char * err_start = "get_command_data() failed on request for: ";
48 char err[strlen(err_start) + strlen(dsc_short) + 1];
49 sprintf(err, "%s%s", err_start, dsc_short);
50 exit_err(i == world.cmd_db.n, err);
56 extern void init_command_db()
58 char * f_name = "init_command_db()";
59 char * path = "confclient/commands";
60 FILE * file = try_fopen(path, "r", f_name);
62 uint32_t linemax = textfile_sizes(file, &lines);
63 char line[linemax + 1];
64 world.cmd_db.cmds = try_malloc(lines * sizeof(struct Command), f_name);
67 while (try_fgets(line, linemax + 1, file, f_name))
69 if ('\n' == line[0] || 0 == line[0])
73 copy_tokenized_string(line, &world.cmd_db.cmds[i].dsc_short, delim);
74 copy_tokenized_string(NULL, &world.cmd_db.cmds[i].server_msg, delim);
75 if (!strcmp("0", world.cmd_db.cmds[i].server_msg))
76 { /* .server_msg==0 detects */
77 free(world.cmd_db.cmds[i].server_msg); /* non-server commands in */
78 world.cmd_db.cmds[i].server_msg = NULL;/* control.h's try_key() / */
79 } /* try_server_command(). */
80 char * arg_string = strtok(NULL, delim);
81 world.cmd_db.cmds[i].arg = arg_string[0];
82 copy_tokenized_string(NULL, &world.cmd_db.cmds[i].dsc_long, "\n");
85 try_fclose(file, f_name);
86 world.cmd_db.n = lines;
87 set_cleanup_flag(CLEANUP_COMMANDS);
92 extern void free_command_db()
95 while (i < world.cmd_db.n)
97 free(world.cmd_db.cmds[i].dsc_short);
98 free(world.cmd_db.cmds[i].dsc_long);
99 free(world.cmd_db.cmds[i].server_msg);
102 free(world.cmd_db.cmds);