From 97a093c52f87dbfb0c800dd09a23436479e69861 Mon Sep 17 00:00:00 2001 From: Khaled Hosny Date: Mon, 12 Oct 2020 15:32:22 +0200 Subject: [PATCH] [hb-subset] Improve error handling a bit * Check that output-file option is actually set before trying to open it. * Print file name and errno when opening the output file fails. * Be more resilient when writing output file and use ferror() to check for errors. Fixes https://github.com/harfbuzz/harfbuzz/issues/2711 --- util/hb-subset.cc | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/util/hb-subset.cc b/util/hb-subset.cc index 253e48a0a..97a3a2f32 100644 --- a/util/hb-subset.cc +++ b/util/hb-subset.cc @@ -70,27 +70,27 @@ struct subset_consumer_t hb_bool_t write_file (const char *output_file, hb_blob_t *blob) { - unsigned int data_length; - const char* data = hb_blob_get_data (blob, &data_length); + unsigned int size; + const char* data = hb_blob_get_data (blob, &size); - FILE *fp_out = fopen(output_file, "wb"); - if (!fp_out) { - fprintf(stderr, "Unable to open output file\n"); - return false; - } - int bytes_written = fwrite(data, 1, data_length, fp_out); + if (!output_file) + fail (true, "No output file was specified"); - fclose (fp_out); + FILE *fp = fopen(output_file, "wb"); + if (!fp) + fail (false, "Cannot open output file `%s': %s", + g_filename_display_name (output_file), strerror (errno)); - if (bytes_written == -1) { - fprintf(stderr, "Unable to write output file\n"); - return false; - } - if ((unsigned int) bytes_written != data_length) { - fprintf(stderr, "Expected %u bytes written, got %d\n", data_length, - bytes_written); - return false; + while (size) { + size_t ret = fwrite (data, 1, size, fp); + size -= ret; + data += ret; + if (size && ferror (fp)) + fail (false, "Failed to write output: %s", strerror (errno)); } + + fclose (fp); + return true; }