Add timespec_{read,write}_file() and unit tests

This commit is contained in:
Pim van Pelt
2018-11-04 17:40:12 +01:00
parent 5b79487ab8
commit f5ea934dfb
4 changed files with 110 additions and 1 deletions

BIN
src/.timespec.c.swp Normal file

Binary file not shown.

View File

@ -250,3 +250,83 @@ bool timespec_get_spec(struct mgos_timespec *ts, char *ret, int retlen) {
}
return true;
}
bool timespec_write_file(struct mgos_timespec *ts, const char *fn) {
char buf[500];
int fd;
if (!timespec_get_spec(ts, buf, sizeof(buf))) {
LOG(LL_ERROR, ("Could not convert timespec to string"));
return false;
}
if (!fn) {
return false;
}
if (!(fd = open(fn, O_RDWR | O_CREAT | O_TRUNC))) {
LOG(LL_ERROR, ("Could not open %s for writing", fn));
return false;
}
if ((uint32_t)strlen(buf) != (uint32_t)write(fd, buf, strlen(buf))) {
LOG(LL_ERROR, ("Short write on %s for data '%s'", fn, buf));
return false;
}
close(fd);
return true;
}
bool timespec_read_file(struct mgos_timespec *ts, const char *fn) {
int fd;
char * buf;
char * spec;
char * buf_ptr;
struct stat fp_stat;
if (!ts) {
return false;
}
if (!fn) {
return false;
}
if (0 != stat(fn, &fp_stat)) {
LOG(LL_ERROR, ("Could not stat %s", fn));
}
if (fp_stat.st_size > 1024) {
LOG(LL_ERROR, ("File size of %s is larger than 1024 bytes (%u)", fn, (uint32_t)fp_stat.st_size));
}
buf = malloc(fp_stat.st_size + 1);
if (!buf) {
LOG(LL_ERROR, ("Could not malloc %u bytes for file %s", (uint32_t)fp_stat.st_size, fn));
}
if (!(fd = open(fn, O_RDONLY))) {
LOG(LL_ERROR, ("Could not open %s for reading", fn));
free(buf);
return false;
}
if (fp_stat.st_size != read(fd, buf, fp_stat.st_size)) {
LOG(LL_ERROR, ("Could not read %u bytes from %s", (uint32_t)fp_stat.st_size, fn));
close(fd);
free(buf);
return false;
}
buf[fp_stat.st_size] = '\0';
close(fd);
LOG(LL_INFO, ("buf='%s'", buf));
// Wipe the timespec and parse back
timespec_clear_spec(ts);
buf_ptr = buf;
while ((spec = strtok_r(buf_ptr, ",", &buf_ptr))) {
if (!timespec_add_spec(ts, spec)) {
LOG(LL_WARN, ("Could not add spec '%s'", spec));
}
}
free(buf);
return true;
}