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