From 0190b4460094e77f26d26808b9d7d34daf18ff84 Mon Sep 17 00:00:00 2001 From: Joseph Hunkeler Date: Thu, 15 Aug 2024 09:33:11 -0400 Subject: Replace the original file instead of using rename() * rename() cannot operate across file system boundaries --- src/relocation.c | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/relocation.c b/src/relocation.c index a86530d..852aca4 100644 --- a/src/relocation.c +++ b/src/relocation.c @@ -115,7 +115,7 @@ int file_replace_text(const char* filename, const char* target, const char* repl return -1; } - tfp = fopen(tempfilename, "w"); + tfp = fopen(tempfilename, "w+"); if (!tfp) { SYSERROR("unable to open temporary fp for writing: %s", tempfilename); fclose(fp); @@ -124,7 +124,7 @@ int file_replace_text(const char* filename, const char* target, const char* repl // Write modified strings to temporary file result = 0; - while (fgets(buffer, sizeof(buffer), fp)) { + while (fgets(buffer, sizeof(buffer), fp) != NULL) { if (strstr(buffer, target)) { if (replace_text(buffer, target, replacement, flags)) { result = -1; @@ -132,12 +132,24 @@ int file_replace_text(const char* filename, const char* target, const char* repl } fputs(buffer, tfp); } + fflush(tfp); + // Replace original with modified copy + fclose(fp); + fp = fopen(filename, "w+"); + if (!fp) { + SYSERROR("unable to reopen %s for writing", filename); + return -1; + } + + // Update original file + rewind(tfp); + while (fgets(buffer, sizeof(buffer), tfp) != NULL) { + fputs(buffer, fp); + } fclose(fp); fclose(tfp); - // Replace original with modified copy - remove(filename); - rename(tempfilename, filename); + remove(tempfilename); return result; } \ No newline at end of file -- cgit