1#include <stdlib.h>
2#include <stdio.h>
3#include <string.h>
4
5#include "util.h"
6
7#define BUF_SIZE 100
8
9char* copy_achar(const char* src)
10{
11 int len = strlen(src) + 1;
12 char* dest = (char*)malloc(sizeof(char)*len);
13 strcpy(dest, src);
14
15 return dest;
16}
17
18int load_or_save_db(sqlite3 *pInMemory, const char *zFilename, int isSave)
19{
20 int rc; /* Function return code */
21 sqlite3 *pFile; /* Database connection opened on zFilename */
22 sqlite3_backup *pBackup; /* Backup object used to copy data */
23 sqlite3 *pTo; /* Database to copy to (pFile or pInMemory) */
24 sqlite3 *pFrom; /* Database to copy from (pFile or pInMemory) */
25
26 rc = sqlite3_open(zFilename, &pFile);
27 if( rc==SQLITE_OK ) {
28 pFrom = (isSave ? pInMemory : pFile);
29 pTo = (isSave ? pFile : pInMemory);
30
31 pBackup = sqlite3_backup_init(pTo, "main", pFrom, "main");
32 if( pBackup ) {
33 (void)sqlite3_backup_step(pBackup, -1);
34 (void)sqlite3_backup_finish(pBackup);
35 }
36 rc = sqlite3_errcode(pTo);
37 }
38
39 (void)sqlite3_close(pFile);
40 return rc;
41}
42
43unsigned int count_file_lines(FILE *file)
44{
45 char buf[BUF_SIZE];
46 unsigned int counter = 0;
47 for(;;) {
48 size_t res = fread(buf, 1, BUF_SIZE, file);
49 if (ferror(file))
50 return -1;
51
52 size_t i;
53 for(i = 0; i < res; i++)
54 if (buf[i] == '\n')
55 counter++;
56
57 if (feof(file))
58 break;
59 }
60
61 return counter;
62}