1#include <locale.h>
2#include <stdio.h>
3#include <sqlite3.h>
4#include <ncurses.h>
5#include "data.h"
6#include "ui.h"
7
8#define BUF_SIZE 100
9
10unsigned int count_lines(FILE* file);
11int load_or_save_db(sqlite3 *pInMemory, const char *zFilename, int isSave);
12
13int main() {
14 Data *data = new_data(":memory:");
15 bootstrap(data);
16
17 setlocale(LC_ALL, "");
18 noecho();
19 cbreak();
20 nonl();
21 keypad(stdscr, TRUE);
22 initscr();
23
24 FILE *f = fopen("dict.txt", "r");
25 unsigned int lines = count_lines(f);
26 fseek(f, 0, SEEK_SET);
27
28 char * line = NULL;
29 size_t len = 0;
30 ssize_t read;
31 PROGRESS_BAR *bar = new_progress_bar(stdscr, lines);
32 while ((read = getline(&line, &len, f)) != -1) {
33 if (line[0] == '#' || line[0] == '\n')
34 continue;
35
36 insert(data, line, read-1);
37 bar_step(bar, 1);
38 }
39
40 move(2,0);
41 printw("Saving db...");
42 refresh();
43 load_or_save_db(data->db, "backup.db", 1);
44
45 clear();
46 refresh();
47
48 TEXT_BOX *box = new_text_box(stdscr, 10);
49 get_char(box);
50
51 clear();
52 refresh();
53
54 endwin();
55
56 free_data(data);
57 return 0;
58}
59
60int load_or_save_db(sqlite3 *pInMemory, const char *zFilename, int isSave){
61 int rc; /* Function return code */
62 sqlite3 *pFile; /* Database connection opened on zFilename */
63 sqlite3_backup *pBackup; /* Backup object used to copy data */
64 sqlite3 *pTo; /* Database to copy to (pFile or pInMemory) */
65 sqlite3 *pFrom; /* Database to copy from (pFile or pInMemory) */
66
67 rc = sqlite3_open(zFilename, &pFile);
68 if( rc==SQLITE_OK ){
69 pFrom = (isSave ? pInMemory : pFile);
70 pTo = (isSave ? pFile : pInMemory);
71
72 pBackup = sqlite3_backup_init(pTo, "main", pFrom, "main");
73 if( pBackup ){
74 (void)sqlite3_backup_step(pBackup, -1);
75 (void)sqlite3_backup_finish(pBackup);
76 }
77 rc = sqlite3_errcode(pTo);
78 }
79
80 (void)sqlite3_close(pFile);
81 return rc;
82}
83
84unsigned int count_lines(FILE* file)
85{
86 char buf[BUF_SIZE];
87 unsigned int counter = 0;
88 for(;;)
89 {
90 size_t res = fread(buf, 1, BUF_SIZE, file);
91 if (ferror(file))
92 return -1;
93
94 size_t i;
95 for(i = 0; i < res; i++)
96 if (buf[i] == '\n')
97 counter++;
98
99 if (feof(file))
100 break;
101 }
102
103 return counter;
104}