- while ((n = emacs_read (ifd, buf, sizeof buf)) > 0)
- if (emacs_write_sig (ofd, buf, n) != n)
- report_file_error ("Write error", newname);
+ while (true)
+ {
+ char buf[MAX_ALLOCA];
+ ptrdiff_t n = emacs_read (ifd, buf, sizeof buf);
+ if (n < 0)
+ report_file_error ("Read error", file);
+ if (n == 0)
+ break;
+ if (emacs_write_sig (ofd, buf, n) != n)
+ report_file_error ("Write error", newname);
+ newsize += n;
+ }
+
+ /* Truncate any existing output file after writing the data. This
+ is more likely to work than truncation before writing, if the
+ file system is out of space or the user is over disk quota. */
+ if (newsize < oldsize && ftruncate (ofd, newsize) != 0)
+ report_file_error ("Truncating output file", newname);
+