1 /**
2 * Dailyjournal is an easy tool to log daily activities
3 * Copyright (C) 2022 Aaron Ball <nullspoon@oper.io>
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18 #include "common.h"
19
20 void get_user_editor(char* editor) {
21 if(getenv("EDITOR") != NULL)
22 strcpy(editor, getenv("EDITOR"));
23 else
24 strcpy(editor, "vi");
25 }
26
27 int fedit(char* path) {
28 char editor[256];
29 char cmd[512];
30 get_user_editor(editor);
31 sprintf(cmd, "%s %s", editor, path);
32 return system(cmd);
33 }
34
35 int fexists(char* path) {
36 FILE* fd = fopen(path, "r");
37 if(!fd)
38 return 0;
39 fclose(fd);
40 return 1;
41 }
42
43 int safe_cp(char* src, char* dest) {
44 FILE* fdsrc = NULL;
45 FILE* fddest = NULL;
46 char c = '\0';
47
48 fdsrc = fopen(src, "r");
49 if(!fdsrc)
50 return -2;
51
52 // Open destination file for appending, juuuuust in case it already exists
53 fddest = fopen(dest, "r");
54 if(fddest) {
55 fclose(fddest);
56 fclose(fdsrc);
57 return 0;
58 }
59
60 fddest = fopen(dest, "a+");
61 if(! fddest)
62 return -2;
63
64 while((c = fgetc(fdsrc)) != EOF)
65 fputc(c, fddest);
66
67 fclose(fdsrc);
68 fclose(fddest);
69 return 0;
70 }
71
72 void getdate(int days, char* out, int outsize) {
73 time_t t;
74 struct tm* tmnow;
75
76 t = time(NULL);
77 t = t + (days * 86400);
78 tmnow = localtime(&t);
79
80 strftime(out, outsize, "%F", tmnow);
81 }
82
83 void getpath(char* base, int days, char* out, char* extension) {
84 char filename[128];
85 // time_t t;
86 // struct tm* tmnow;
87 // t = time(NULL);
88 // t = t + (days * 86400);
89 // tmnow = localtime(&t);
90
91 //strftime(filename, 256, "%F", tmnow);
92
93 getdate(days, filename, 128);
94
95 sprintf(out, "%s/%s%s", base, filename, extension);
96 }
97
98 int env_if_set(char* buf, char* varname) {
99 char* env = getenv(varname);
100 if(env != NULL) {
101 sprintf(buf, "%s", env);
102 return 0;
103 }
104 return 1;
105 }
|