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, sprintf() */
7 #include <stdlib.h> /* free() */
8 #include <string.h> /* memset(), strlen(), strcmp() */
9 #include "../common/err_try_fgets.h" /* reset_err_try_fgets_counter() */
10 #include "../common/readwrite.h" /* try_fopen(),try_fclose(),textfile_width() */
11 #include "../common/rexit.h" /* exit_trouble() */
12 #include "../common/try_malloc.h" /* try_malloc() */
13 #include "array_append.h" /* array_append() */
14 #include "world.h" /* global world */
15 #include "cleanup.h" /* set_cleanup_flag() */
19 /* Helper to init_command_db(). */
20 static void write_line_to_target(char ** target, char * line)
22 char * f_name = "write_line_to_target()";
23 *target = try_malloc(strlen(line), f_name);
24 line[strlen(line) - 1] = '\0';
25 sprintf(*target, "%s", line);
30 extern struct Command * get_command(char * dsc_short)
32 struct Command * cmd_ptr = world.commandDB.cmds;
34 while (i < world.commandDB.n)
36 if (0 == strcmp(dsc_short, cmd_ptr->dsc_short))
40 cmd_ptr = &cmd_ptr[1];
48 extern void init_command_db()
50 char * f_name = "init_command_db()";
51 char * context = "Failed reading command DB file. ";
52 FILE * file = try_fopen(world.path_commands, "r", f_name);
53 uint32_t linemax = textfile_width(file);
54 char line[linemax + 1];
55 reset_err_try_fgets_counter();
59 int test_for_end = try_fgetc(file, f_name);
60 if (EOF == test_for_end || '\n' == test_for_end)
64 exit_trouble(EOF == ungetc(test_for_end, file), f_name, "ungetc()");
66 memset(&cmd, 0, sizeof(struct Command));
67 err_try_fgets(line, linemax, file, context, "nf");
68 write_line_to_target(&cmd.dsc_short, line);
69 err_try_fgets(line, linemax, file, context, "0nf");
70 write_line_to_target(&cmd.dsc_long, line);
71 err_try_fgets(line, linemax, file, context, "0nf");
72 if (strcmp(world.delim, line))
74 write_line_to_target(&cmd.server_msg, line);
75 err_try_fgets(line, linemax, file, context, "0nfs");
77 err_try_fgets(line, linemax, file, context, "d");
79 array_append(i, sizeof(struct Command), (void *) &cmd,
80 (void **) &world.commandDB.cmds);
83 try_fclose(file, f_name);
84 world.commandDB.n = i;
85 set_cleanup_flag(CLEANUP_COMMANDS);
90 extern void free_command_db()
93 while (i < world.commandDB.n)
95 free(world.commandDB.cmds[i].dsc_short);
96 free(world.commandDB.cmds[i].dsc_long);
97 free(world.commandDB.cmds[i].server_msg);
100 free(world.commandDB.cmds);