2022-01-17 14:44:59 +00:00
|
|
|
#include "fs.h"
|
2023-03-27 14:11:39 -03:00
|
|
|
#include "printf.h"
|
2022-01-17 14:44:59 +00:00
|
|
|
|
|
|
|
struct mg_fd *mg_fs_open(struct mg_fs *fs, const char *path, int flags) {
|
|
|
|
struct mg_fd *fd = (struct mg_fd *) calloc(1, sizeof(*fd));
|
|
|
|
if (fd != NULL) {
|
2022-02-08 13:36:04 +00:00
|
|
|
fd->fd = fs->op(path, flags);
|
2022-01-17 14:44:59 +00:00
|
|
|
fd->fs = fs;
|
|
|
|
if (fd->fd == NULL) {
|
|
|
|
free(fd);
|
|
|
|
fd = NULL;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return fd;
|
|
|
|
}
|
|
|
|
|
|
|
|
void mg_fs_close(struct mg_fd *fd) {
|
|
|
|
if (fd != NULL) {
|
2022-02-08 13:36:04 +00:00
|
|
|
fd->fs->cl(fd->fd);
|
2022-01-17 14:44:59 +00:00
|
|
|
free(fd);
|
|
|
|
}
|
|
|
|
}
|
2022-01-18 17:11:02 +00:00
|
|
|
|
|
|
|
char *mg_file_read(struct mg_fs *fs, const char *path, size_t *sizep) {
|
|
|
|
struct mg_fd *fd;
|
|
|
|
char *data = NULL;
|
|
|
|
size_t size = 0;
|
2022-02-08 13:36:04 +00:00
|
|
|
fs->st(path, &size, NULL);
|
2022-01-18 17:11:02 +00:00
|
|
|
if ((fd = mg_fs_open(fs, path, MG_FS_READ)) != NULL) {
|
|
|
|
data = (char *) calloc(1, size + 1);
|
|
|
|
if (data != NULL) {
|
2022-02-08 13:36:04 +00:00
|
|
|
if (fs->rd(fd->fd, data, size) != size) {
|
2022-01-18 17:11:02 +00:00
|
|
|
free(data);
|
|
|
|
data = NULL;
|
|
|
|
} else {
|
|
|
|
data[size] = '\0';
|
|
|
|
if (sizep != NULL) *sizep = size;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
mg_fs_close(fd);
|
|
|
|
}
|
|
|
|
return data;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool mg_file_write(struct mg_fs *fs, const char *path, const void *buf,
|
|
|
|
size_t len) {
|
|
|
|
bool result = false;
|
2022-08-15 16:08:34 +01:00
|
|
|
struct mg_fd *fd;
|
|
|
|
char tmp[MG_PATH_MAX];
|
|
|
|
mg_snprintf(tmp, sizeof(tmp), "%s..%d", path, rand());
|
|
|
|
if ((fd = mg_fs_open(fs, tmp, MG_FS_WRITE)) != NULL) {
|
2022-02-08 13:36:04 +00:00
|
|
|
result = fs->wr(fd->fd, buf, len) == len;
|
2022-01-18 17:11:02 +00:00
|
|
|
mg_fs_close(fd);
|
2022-08-15 16:08:34 +01:00
|
|
|
if (result) {
|
|
|
|
fs->rm(path);
|
|
|
|
fs->mv(tmp, path);
|
|
|
|
} else {
|
|
|
|
fs->rm(tmp);
|
|
|
|
}
|
2022-01-18 17:11:02 +00:00
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool mg_file_printf(struct mg_fs *fs, const char *path, const char *fmt, ...) {
|
|
|
|
va_list ap;
|
2022-08-13 15:37:55 +01:00
|
|
|
char *data;
|
|
|
|
bool result = false;
|
2022-01-18 17:11:02 +00:00
|
|
|
va_start(ap, fmt);
|
2022-08-13 15:37:55 +01:00
|
|
|
data = mg_vmprintf(fmt, &ap);
|
2022-01-18 17:11:02 +00:00
|
|
|
va_end(ap);
|
2022-08-13 15:37:55 +01:00
|
|
|
result = mg_file_write(fs, path, data, strlen(data));
|
|
|
|
free(data);
|
2022-01-18 17:11:02 +00:00
|
|
|
return result;
|
|
|
|
}
|