diff options
Diffstat (limited to 'src/fileutils.c')
-rw-r--r-- | src/fileutils.c | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/src/fileutils.c b/src/fileutils.c index ea57550..fe9ab88 100644 --- a/src/fileutils.c +++ b/src/fileutils.c @@ -5,6 +5,7 @@ #include <stdlib.h> #include <string.h> #include <errno.h> +#include <limits.h> #include <pwd.h> #include <unistd.h> #include <fcntl.h> @@ -80,3 +81,57 @@ int create_directory_recursive(char *path) { } return 0; } + +int file_exists(const char *path) { + struct stat st; + return stat(path, &st); +} + +int create_lock_file(const char *path) { + int fd = open(path, O_CREAT | O_EXCL); + if(fd == -1) + return errno; + fsync(fd); + return close(fd); +} + +int file_overwrite(const char *filepath, const char *data, size_t size) { + FILE *file = fopen(filepath, "wb"); + if(!file) { + int err = -errno; + perror(filepath); + return err; + } + + unsigned long bytes_written = fwrite(data, 1, size, file); + if(bytes_written != size) { + fprintf(stderr, "Failed to write all bytes to file %s. Expected to write %zu bytes, only wrote %zu bytes\n", filepath, size, bytes_written); + fclose(file); + return -1; + } + + fclose(file); + return 0; +} + +int file_overwrite_in_dir(const char *dir, const char *filename, const char *data, size_t size) { + char filepath[PATH_MAX]; + const char *filepath_components[] = { dir, filename }; + path_join(filepath, filepath_components, 2); + return file_overwrite(filepath, data, size); +} + +void path_join(char *output, const char **components, int num_components) { + int offset = 0; + for(int i = 0; i < num_components; ++i) { + if(i > 0) { + output[offset] = '/'; + ++offset; + } + + int component_len = strlen(components[i]); + memcpy(output + offset, components[i], component_len); + offset += component_len; + } + output[offset] = '\0'; +} |