From d102e028aee6571c0fd9dfd4074cfb3c15f4594e Mon Sep 17 00:00:00 2001 From: "Gabriel A. Giovanini" Date: Sat, 17 Feb 2024 11:41:23 +0100 Subject: ref: Refactor newer folder structure Create a lib dict and importer project. * dict: holds the main application * importer: code to read from source to a common database. * lib: shared code --- lib/util.c | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 lib/util.c (limited to 'lib/util.c') diff --git a/lib/util.c b/lib/util.c new file mode 100644 index 0000000..6720082 --- /dev/null +++ b/lib/util.c @@ -0,0 +1,61 @@ +#include +#include +#include + +#include "util.h" + +#define BUF_SIZE 100 + +char* copy_achar(const char* src) { + int len = strlen(src) + 1; + char* dest = (char*)malloc(sizeof(char)*len); + strcpy(dest, src); + + return dest; +} + + +int load_or_save_db(sqlite3 *pInMemory, const char *zFilename, int isSave){ + int rc; /* Function return code */ + sqlite3 *pFile; /* Database connection opened on zFilename */ + sqlite3_backup *pBackup; /* Backup object used to copy data */ + sqlite3 *pTo; /* Database to copy to (pFile or pInMemory) */ + sqlite3 *pFrom; /* Database to copy from (pFile or pInMemory) */ + + rc = sqlite3_open(zFilename, &pFile); + if( rc==SQLITE_OK ){ + pFrom = (isSave ? pInMemory : pFile); + pTo = (isSave ? pFile : pInMemory); + + pBackup = sqlite3_backup_init(pTo, "main", pFrom, "main"); + if( pBackup ){ + (void)sqlite3_backup_step(pBackup, -1); + (void)sqlite3_backup_finish(pBackup); + } + rc = sqlite3_errcode(pTo); + } + + (void)sqlite3_close(pFile); + return rc; +} + +unsigned int count_file_lines(FILE *file) { + char buf[BUF_SIZE]; + unsigned int counter = 0; + for(;;) + { + size_t res = fread(buf, 1, BUF_SIZE, file); + if (ferror(file)) + return -1; + + size_t i; + for(i = 0; i < res; i++) + if (buf[i] == '\n') + counter++; + + if (feof(file)) + break; + } + + return counter; +} -- cgit v1.2.3