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