[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

View File

@ -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;
}