Changed all the sscanf calls to use the %n directive. By comparing the
[ctodo.git] / del.c
blob96ff2d0e120c4317b179143140d67de73a5417a4
1 #include <del.h>
2 #include <stdio.h>
3 #include <readline/readline.h>
4 #include <stdlib.h>
5 #include <string.h>
7 void del_help() {
8 printf(" Usage: del TODO#\n");
11 int del(sqlite3 *db, MArray tokens) {
12 char *query;
13 char *confirmation;
14 char *errmsg;
15 int todo;
16 int retVal;
17 int parsed;
18 int hasChildren = 0;
19 sqlite3_stmt *statement;
21 if (tokens->len == 2 && !strcmp(myarray_get(tokens, char *, 1), "help")) {
22 del_help();
23 return 0;
24 } else if (tokens->len != 2) {
25 printf("Invalid amount of arguments.\n");
26 del_help();
28 return 0;
31 if (sscanf(myarray_get(tokens, char *, 1), "%d%n", &todo, &parsed) < 1 || parsed != strlen(myarray_get(tokens, char *, 1)) || todo < 0) {
32 printf("Invalid argument. TODO# must be a positive integer.\n");
33 return 0;
36 query = sqlite3_mprintf("SELECT COUNT(key) FROM todo WHERE parent = %d;", todo);
38 retVal = sqlite3_prepare_v2(db, query, -1, &statement, NULL);
39 sqlite3_free(query);
40 if (retVal != SQLITE_OK) {
41 printf("An error occurred while trying to get the data from the database.\n");
42 sqlite3_finalize(statement);
43 return 1;
46 while ((retVal = sqlite3_step(statement)) == SQLITE_ROW) {
47 hasChildren = sqlite3_column_int(statement, 0);
49 sqlite3_finalize(statement);
51 if (hasChildren) {
52 printf("This todo has children. Do you want to delete them too?\n");
53 printf("Saying no will make these children parentless (toplevel todo's).\n");
54 confirmation = readline("yes/no (default is no)? ");
56 if (confirmation != NULL && !strncmp(confirmation, "y", 1)) {
57 query = sqlite3_mprintf("DELETE FROM todo WHERE parent = %d;", todo);
58 sqlite3_exec(db, query, NULL, NULL, &errmsg);
59 sqlite3_free(errmsg);
60 sqlite3_free(query);
61 } else {
62 query = sqlite3_mprintf("UPDATE todo SET parent = NULL WHERE parent = %d;\n", todo);
63 sqlite3_exec(db, query, NULL, NULL, &errmsg);
64 sqlite3_free(errmsg);
65 sqlite3_free(query);
68 if (confirmation != NULL) free(confirmation);
71 query = sqlite3_mprintf("DELETE FROM todo WHERE key = %d;", todo);
72 sqlite3_exec(db, query, NULL, NULL, &errmsg);
73 sqlite3_free(errmsg);
74 sqlite3_free(query);
76 return 0;