forked from iizukanao/picam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.c
132 lines (121 loc) · 2.74 KB
/
state.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#include "state.h"
// Create state dir if it does not exist
int state_create_dir(char *dir) {
struct stat st;
int err;
err = stat(dir, &st);
if (err == -1) {
if (errno == ENOENT) {
// create directory
if (mkdir(dir, 0755) == 0) { // success
fprintf(stderr, "created state dir: ./%s\n", dir);
} else { // error
fprintf(stderr, "error creating state dir (./%s): %s\n",
dir, strerror(errno));
return -1;
}
} else {
perror("stat state dir");
return -1;
}
} else {
if (!S_ISDIR(st.st_mode)) {
fprintf(stderr, "state dir (./%s) is not a directory\n",
dir);
return -1;
}
}
if (access(dir, R_OK) != 0) {
fprintf(stderr, "Can't access state dir (./%s): %s\n",
dir, strerror(errno));
return -1;
}
return 0;
}
void state_set(char *dir, char *name, char *value) {
FILE *fp;
char *path;
int path_len;
struct stat st;
int err;
err = stat(dir, &st);
if (err == -1) {
if (errno == ENOENT) {
fprintf(stderr, "Error: %s directory does not exist\n", dir);
} else {
perror("stat error");
}
exit(EXIT_FAILURE);
} else {
if (!S_ISDIR(st.st_mode)) {
fprintf(stderr, "Error: %s is not a directory\n", dir);
exit(EXIT_FAILURE);
}
}
path_len = strlen(dir) + strlen(name) + 2;
path = malloc(path_len);
if (path == NULL) {
perror("malloc path");
return;
}
snprintf(path, path_len, "%s/%s", dir, name);
fp = fopen(path, "w");
if (fp == NULL) {
perror("State file open failed");
return;
}
fwrite(value, 1, strlen(value), fp);
fclose(fp);
free(path);
}
void state_get(char *dir, char *name, char **buf) {
FILE *fp;
char *path;
int path_len;
int size;
struct stat st;
int err;
err = stat(dir, &st);
if (err == -1) {
if (errno == ENOENT) {
fprintf(stderr, "Error: %s directory does not exist\n", dir);
} else {
perror("stat error");
}
exit(EXIT_FAILURE);
} else {
if (!S_ISDIR(st.st_mode)) {
fprintf(stderr, "Error: %s is not a directory\n", dir);
exit(EXIT_FAILURE);
}
}
path_len = strlen(dir) + strlen(name) + 2;
path = malloc(path_len);
if (path == NULL) {
perror("malloc path");
return;
}
snprintf(path, path_len, "%s/%s", dir, name);
fp = fopen(path, "r");
if (fp == NULL) {
perror("State file open failed");
return;
}
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fseek(fp, 0, SEEK_SET);
*buf = malloc(size);
if (*buf == NULL) {
perror("Can't malloc for buffer");
return;
}
fread(*buf, 1, size, fp);
fclose(fp);
free(path);
}