From 1dc10dd269d180cb33ad31dce597170e5090d502 Mon Sep 17 00:00:00 2001 From: "B. Watson" Date: Wed, 26 Nov 2025 16:49:33 -0500 Subject: alf: Don't create output file until the first input file is successfully crunched (avoids 0-byte turds in case of error). --- src/alf.c | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/src/alf.c b/src/alf.c index 4fca2f3..e47320a 100644 --- a/src/alf.c +++ b/src/alf.c @@ -256,6 +256,13 @@ void crunch(void) { update_header(); } +void make_backup(void) { + char bak[PATH_MAX + 2]; + strncpy(bak, out_filename, PATH_MAX); + strcat(bak, "~"); + rename(out_filename, bak); +} + void crunch_file(const char *filename) { init_table(); @@ -284,14 +291,19 @@ void crunch_file(const char *filename) { /* crunches the entire input to memory! */ crunch(); - fwrite(output_buf, 1, output_len, out_file); -} + /* don't open the output file until crunch() has succeeded once. + this avoids leaving 0-byte turds */ + if(!out_file) { + if(!opt_overwrite) make_backup(); + out_file = fopen(out_filename, opt_append ? "ab" : "wb"); + if(!out_file) { + fprintf(stderr, "%s: fatal: ", self); + perror(out_filename); + exit(1); + } + } -void make_backup(void) { - char bak[PATH_MAX + 2]; - strncpy(bak, out_filename, PATH_MAX); - strcat(bak, "~"); - rename(out_filename, bak); + fwrite(output_buf, 1, output_len, out_file); } void usage(void) { @@ -339,15 +351,6 @@ int main(int argc, char **argv) { exit(1); } - if(!opt_overwrite) make_backup(); - - out_file = fopen(out_filename, opt_append ? "ab" : "wb"); - if(!out_file) { - fprintf(stderr, "%s: fatal: ", self); - perror(out_filename); - exit(1); - } - while(optind < argc) { crunch_file(argv[optind++]); } -- cgit v1.2.3