From bc689cfe7631ea1f8dff4cfa6a6972ad8cea3c63 Mon Sep 17 00:00:00 2001 From: Rui Ueyama Date: Tue, 18 Aug 2020 11:45:59 +0900 Subject: [PATCH] Write to an in-memory buffer before writing to an actual output file We don't want to leave a partial assembly output if the compiler fails during compilation. Technically speaking, there's still a risk of leaving a partially- written output file if the compiler dies during file copy. To fix that, we have to write to a temporary file in the same filesystem as the final output file and rename the temporary file to atomically replace the output file. We don't do that in this patch for the sake of succinctness, though. --- main.c | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/main.c b/main.c index eb31bee..99dc05f 100644 --- a/main.c +++ b/main.c @@ -271,9 +271,19 @@ static void cc1(void) { Var *prog = parse(tok); + // Open a temporary output buffer. + char *buf; + size_t buflen; + FILE *output_buf = open_memstream(&buf, &buflen); + // Traverse the AST to emit assembly. + codegen(prog, output_buf); + fclose(output_buf); + + // Write the asembly text to a file. FILE *out = open_file(output_file); - codegen(prog, out); + fwrite(buf, buflen, 1, out); + fclose(out); } static void assemble(char *input, char *output) { -- GitLab