[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
This commit is contained in:
Khaled Hosny 2020-10-12 15:32:22 +02:00 committed by Behdad Esfahbod
parent fa771a7f85
commit 97a093c52f
1 changed files with 17 additions and 17 deletions

View File

@ -70,27 +70,27 @@ struct subset_consumer_t
hb_bool_t hb_bool_t
write_file (const char *output_file, hb_blob_t *blob) { write_file (const char *output_file, hb_blob_t *blob) {
unsigned int data_length; unsigned int size;
const char* data = hb_blob_get_data (blob, &data_length); const char* data = hb_blob_get_data (blob, &size);
FILE *fp_out = fopen(output_file, "wb"); if (!output_file)
if (!fp_out) { fail (true, "No output file was specified");
fprintf(stderr, "Unable to open output file\n");
return false;
}
int bytes_written = fwrite(data, 1, data_length, fp_out);
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) { while (size) {
fprintf(stderr, "Unable to write output file\n"); size_t ret = fwrite (data, 1, size, fp);
return false; size -= ret;
} data += ret;
if ((unsigned int) bytes_written != data_length) { if (size && ferror (fp))
fprintf(stderr, "Expected %u bytes written, got %d\n", data_length, fail (false, "Failed to write output: %s", strerror (errno));
bytes_written);
return false;
} }
fclose (fp);
return true; return true;
} }