diff options
Diffstat (limited to 'src/common.c')
-rw-r--r-- | src/common.c | 105 |
1 files changed, 105 insertions, 0 deletions
diff --git a/src/common.c b/src/common.c new file mode 100644 index 0000000..062c6dd --- /dev/null +++ b/src/common.c @@ -0,0 +1,105 @@ +/** + * Dailyjournal is an easy tool to log daily activities + * Copyright (C) 2022 Aaron Ball <nullspoon@oper.io> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ +#include "common.h" + +void get_user_editor(char* editor) { + if(getenv("EDITOR") != NULL) + strcpy(editor, getenv("EDITOR")); + else + strcpy(editor, "vi"); +} + +int fedit(char* path) { + char editor[256]; + char cmd[512]; + get_user_editor(editor); + sprintf(cmd, "%s %s", editor, path); + return system(cmd); +} + +int fexists(char* path) { + FILE* fd = fopen(path, "r"); + if(!fd) + return 0; + fclose(fd); + return 1; +} + +int safe_cp(char* src, char* dest) { + FILE* fdsrc = NULL; + FILE* fddest = NULL; + char c = '\0'; + + fdsrc = fopen(src, "r"); + if(!fdsrc) + return -2; + + // Open destination file for appending, juuuuust in case it already exists + fddest = fopen(dest, "r"); + if(fddest) { + fclose(fddest); + fclose(fdsrc); + return 0; + } + + fddest = fopen(dest, "a+"); + if(! fddest) + return -2; + + while((c = fgetc(fdsrc)) != EOF) + fputc(c, fddest); + + fclose(fdsrc); + fclose(fddest); + return 0; +} + +void getdate(int days, char* out, int outsize) { + time_t t; + struct tm* tmnow; + + t = time(NULL); + t = t + (days * 86400); + tmnow = localtime(&t); + + strftime(out, outsize, "%F", tmnow); +} + +void getpath(char* base, int days, char* out, char* extension) { + char filename[128]; + // time_t t; + // struct tm* tmnow; + // t = time(NULL); + // t = t + (days * 86400); + // tmnow = localtime(&t); + + //strftime(filename, 256, "%F", tmnow); + + getdate(days, filename, 128); + + sprintf(out, "%s/%s%s", base, filename, extension); +} + +int env_if_set(char* buf, char* varname) { + char* env = getenv(varname); + if(env != NULL) { + sprintf(buf, "%s", env); + return 0; + } + return 1; +} |