1#include <locale.h>
2#include <stdio.h>
3#include <sqlite3.h>
4#include <ncurses.h>
5#include "data.h"
6
7#define BUF_SIZE 100
8
9unsigned int count_lines(FILE* file);
10int load_or_save_db(sqlite3 *pInMemory, const char *zFilename, int isSave);
11
12int main() {
13 Data *data = new_data(":memory:");
14
15 bootstrap(data);
16
17 setlocale(LC_ALL, "");
18 initscr();
19
20 int maxx=getmaxx(stdscr);
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 int count = 0;
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 count ++;
36 move(0,0);
37 float total = ((float)count/(float)lines);
38 printw("%03.0f%% ", total*100);
39 for (int x = 0; x < ((maxx-4)*total); x++) {
40 printw("█");
41 }
42 move(1,0);
43 printw("%d/%d",count,lines);
44 refresh();
45 }
46
47 move(2,0);
48 printw("Saving db...");
49 refresh();
50 load_or_save_db(data->db, "backup.db", 1);
51
52 clear();
53 refresh();
54 return 0;
55}
56
57int load_or_save_db(sqlite3 *pInMemory, const char *zFilename, int isSave){
58 int rc; /* Function return code */
59 sqlite3 *pFile; /* Database connection opened on zFilename */
60 sqlite3_backup *pBackup; /* Backup object used to copy data */
61 sqlite3 *pTo; /* Database to copy to (pFile or pInMemory) */
62 sqlite3 *pFrom; /* Database to copy from (pFile or pInMemory) */
63
64 rc = sqlite3_open(zFilename, &pFile);
65 if( rc==SQLITE_OK ){
66 pFrom = (isSave ? pInMemory : pFile);
67 pTo = (isSave ? pFile : pInMemory);
68
69 pBackup = sqlite3_backup_init(pTo, "main", pFrom, "main");
70 if( pBackup ){
71 (void)sqlite3_backup_step(pBackup, -1);
72 (void)sqlite3_backup_finish(pBackup);
73 }
74 rc = sqlite3_errcode(pTo);
75 }
76
77 (void)sqlite3_close(pFile);
78 return rc;
79}
80
81unsigned int count_lines(FILE* file)
82{
83 char buf[BUF_SIZE];
84 unsigned int counter = 0;
85 for(;;)
86 {
87 size_t res = fread(buf, 1, BUF_SIZE, file);
88 if (ferror(file))
89 return -1;
90
91 size_t i;
92 for(i = 0; i < res; i++)
93 if (buf[i] == '\n')
94 counter++;
95
96 if (feof(file))
97 break;
98 }
99
100 return counter;
101}