From ef6eb96daa662e69f429ac98feeb497127dfbbd9 Mon Sep 17 00:00:00 2001 From: Callum Brown Date: Tue, 13 Oct 2020 18:40:47 +0100 Subject: [PATCH] Prepend temp file to output file --- src/gmsfn.c | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/src/gmsfn.c b/src/gmsfn.c index 8c0ddb6..147cc86 100644 --- a/src/gmsfn.c +++ b/src/gmsfn.c @@ -160,6 +160,37 @@ get_absolute_url(char *url, char *base_url) } +/* Append path2 to path1, delete path2, rename path1 to path2. */ +int +cat_and_rename(char *path1, char *path2) +{ + FILE *fp1 = fopen(path1, "a"); + if (!fp1) { + fprintf(stderr, "Could not open %s for appending.\n", path1); + return 1; + } + FILE *fp2 = fopen(path2, "r"); + if (!fp2) { + fprintf(stderr, "Could not open %s for reading.\n", path2); + return 1; + } + char buf[BUFSIZ]; + while (fgets(buf, BUFSIZ, fp2) != NULL) { + fputs(buf, fp1); + } + fclose(fp1); + fclose(fp2); + if (remove(path2) != 0) { + fprintf(stderr, "Could not delete %s\n", path2); + } + if (rename(path1, path2) != 0) { + fprintf(stderr, "Could not rename %s to %s\n", path1, path2); + return 1; + } + return 0; +} + + int make_response_from_file(struct gemini_response *resp, FILE *fp) { BIO *file = BIO_new_fp(fp, BIO_CLOSE); @@ -243,9 +274,10 @@ main(int argc, char *argv[]) if (token_is_heading(config_tok, 3)) { /* Clear up from previous output file */ if (good_output_file) { - free(tmp_out_path); fclose(tmp_out_fp); free(existing_links); + cat_and_rename(tmp_out_path, out_path); + free(tmp_out_path); } if (!absolute) { free(out_path); @@ -384,9 +416,10 @@ main(int argc, char *argv[]) /* Clear up from previous output file */ if (good_output_file) { - free(tmp_out_path); fclose(tmp_out_fp); free(existing_links); + cat_and_rename(tmp_out_path, out_path); + free(tmp_out_path); } if (!absolute) { free(out_path); -- 2.34.2