From 35aca1f0582c43b5f6818c8fc00b924247e45881 Mon Sep 17 00:00:00 2001 From: dec05eba Date: Wed, 15 Jul 2020 06:09:50 +0200 Subject: Implement rss sync --- src/fileutils.c | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) (limited to 'src/fileutils.c') diff --git a/src/fileutils.c b/src/fileutils.c index 64c7a48..4fba0d0 100644 --- a/src/fileutils.c +++ b/src/fileutils.c @@ -11,7 +11,7 @@ #include #include -const char* get_home_dir() { +const char* get_home_dir(void) { const char *home_dir = getenv("HOME"); if(!home_dir) { struct passwd *pw = getpwuid(getuid()); @@ -38,12 +38,13 @@ int file_get_content(const char *filepath, char **data, long *size) { } fseek(file, 0, SEEK_SET); - *data = alloc_or_crash(*size); + *data = alloc_or_crash(*size + 1); if((long)fread(*data, 1, *size, file) != *size) { fprintf(stderr, "Failed to read all bytes in file %s\n", filepath); result = -1; goto cleanup; } + (*data)[*size] = '\0'; cleanup: fclose(file); @@ -87,10 +88,9 @@ int file_exists(const char *path) { } int create_lock_file(const char *path) { - int fd = open(path, O_CREAT | O_EXCL); + int fd = open(path, O_CREAT | O_EXCL | O_SYNC, 0666); if(fd == -1) return errno; - fsync(fd); return close(fd); } @@ -117,7 +117,17 @@ int file_overwrite_in_dir(const char *dir, const char *filename, const char *dat char filepath[PATH_MAX]; const char *filepath_components[] = { dir, filename }; path_join(filepath, filepath_components, 2); - return file_overwrite(filepath, data, size); + + char tmp_filepath[PATH_MAX]; + strcpy(tmp_filepath, filepath); + strcat(tmp_filepath, ".tmp"); + + int result = file_overwrite(tmp_filepath, data, size); + if(result != 0) + return result; + + /* Rename is atomic! */ + return rename(tmp_filepath, filepath); } void path_join(char *output, const char **components, int num_components) { -- cgit v1.2.3