diff --git a/src/create.c b/src/create.c index e9a19a1..d63f928 100644 --- a/src/create.c +++ b/src/create.c @@ -72,12 +72,24 @@ int create(const char *directory, const char *output_file) { rc = 0; cleanup:; + /* An error that happened before the cleanup owns errno; one raised by the + cleanup itself owns it only when nothing had failed yet. A buffered write + can fail for the first time in fclose, so that errno must survive. */ const int saved_errno = errno; + int cleanup_errno = 0; + free(resolved); unlink(template); - if (tmp != NULL && fclose(tmp) != 0 && rc == 0) - rc = -1; - if (rc == -1) + if (tmp != NULL && fclose(tmp) != 0) + cleanup_errno = errno; + + if (rc == -1) { errno = saved_errno; - return rc; + return -1; + } + if (cleanup_errno != 0) { + errno = cleanup_errno; + return -1; + } + return 0; } diff --git a/src/utility.c b/src/utility.c index e0c5532..d738778 100644 --- a/src/utility.c +++ b/src/utility.c @@ -74,14 +74,26 @@ int copy(const char *src, const char *dst) { rc = 0; cleanup:; + /* An error that happened before the cleanup owns errno; one raised by the + cleanup itself owns it only when nothing had failed yet. A buffered write + can fail for the first time in fclose, so that errno must survive. */ const int saved_errno = errno; - if (file1 != NULL && fclose(file1) != 0 && rc == 0) - rc = -1; - if (file2 != NULL && fclose(file2) != 0 && rc == 0) - rc = -1; - if (rc == -1) + int cleanup_errno = 0; + + if (file1 != NULL && fclose(file1) != 0 && cleanup_errno == 0) + cleanup_errno = errno; + if (file2 != NULL && fclose(file2) != 0 && cleanup_errno == 0) + cleanup_errno = errno; + + if (rc == -1) { errno = saved_errno; - return rc; + return -1; + } + if (cleanup_errno != 0) { + errno = cleanup_errno; + return -1; + } + return 0; } int count_lines(const char *file) {