From cdea6b0e8c1e51c9962f73e183a3bd72ed63b40f Mon Sep 17 00:00:00 2001 From: Louie S Date: Sun, 6 Nov 2022 14:53:23 -0800 Subject: Restructure repository --- src/cache.c | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 src/cache.c (limited to 'src/cache.c') diff --git a/src/cache.c b/src/cache.c new file mode 100644 index 0000000..60a0fa6 --- /dev/null +++ b/src/cache.c @@ -0,0 +1,77 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "include/cache.h" +#include "include/read_cfg.h" + +void save_to_cache(int g_hover, int e_hover, int true_hover, char *cfg_name){ + FILE *fp; + struct stat cfg_stat; //for determining last modification time of file + char *path = get_cache_path(true); + + //ensure get_cache_path() did not return NULL + if(path == NULL) return; + + //open cache file for writing + fp = fopen(path, "wb"); + if(fp == NULL){ + printf("Failed to save cache data: could not open \"%s\"\n", path); + return; + } + + //determine last modification time for cfg file + stat(cfg_name, &cfg_stat); + + //write to file + fwrite(cfg_name, sizeof(char), BUF_LEN, fp); + fwrite(&cfg_stat.st_mtime, sizeof(long int), 1, fp); + fwrite(&g_hover, sizeof(int), 1, fp); + fwrite(&e_hover, sizeof(int), 1, fp); + fwrite(&true_hover, sizeof(int), 1, fp); + + fclose(fp); + return; +} + +void load_cache(int *g_hover, int *e_hover, int *true_hover, char *new_cfg_name){ + FILE *fp; + char *path = get_cache_path(false); + char saved_cfg_name[BUF_LEN]; + long int saved_cfg_mtime; + struct stat new_cfg_stat; + + //ensure get_cache_path() did not return NULL + if(path == NULL) return; + + //open cache file for reading + fp = fopen(path, "rb"); + if(fp == NULL){ + printf("Failed to load cached data: could not open \"%s\"\n", path); + return; + } + + //check that cfg_name matches and is not newer than the cached cfg; if not, do not load from cache + fread(saved_cfg_name, sizeof(char), BUF_LEN, fp); + fread(&saved_cfg_mtime, sizeof(long int), 1, fp); + stat(new_cfg_name, &new_cfg_stat); + + if(!(strcmp(saved_cfg_name, new_cfg_name)) && saved_cfg_mtime >= new_cfg_stat.st_mtime){ + fread(g_hover, sizeof(int), 1, fp); + fread(e_hover, sizeof(int), 1, fp); + fread(true_hover, sizeof(int), 1, fp); + } + + else{ + *g_hover = 0; + *e_hover = 0; + *true_hover = 0; + } + + fclose(fp); + return; +} -- cgit