aboutsummaryrefslogtreecommitdiff
path: root/src/fileutils.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/fileutils.c')
-rw-r--r--src/fileutils.c20
1 files changed, 15 insertions, 5 deletions
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 <fcntl.h>
#include <sys/stat.h>
-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) {