From 7c061ae7c293de0b52bad6a9d51a326005c4395c Mon Sep 17 00:00:00 2001 From: Joseph Hunkeler Date: Thu, 15 Aug 2024 10:04:56 -0400 Subject: indexer: Handle destination directories more gracefully (#28) * Handle destination directories more gracefully * The storage.output_dir is now the storage.root to avoid generating a sub-directory beneath the temporary working directory * The destination directory is created, then resolved by realpath to avoid generating the destination directory within the temporary working directory when a relative path is used as input * Replace the original file instead of using rename() * rename() cannot operate across file system boundaries * Dynamically allocate rootdirs array * Use realpath on positional arguments * Convert all markdown files to HTML * README.html files are considered entry points and are linked as index.html * Assign retcode after indexing --- src/relocation.c | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) (limited to 'src/relocation.c') 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