From: Joey Hess Date: Fri, 11 Apr 2008 20:10:18 +0000 (-0400) Subject: fix edge cases X-Git-Tag: 0.29~11 X-Git-Url: https://err.no/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=ee4e74dd6a20706f29ef30a2613a1977f6f325fa;p=moreutils fix edge cases If a file an exact multiple of the max buffer size were sponged, it would fail at the end due to trying to write 0 remaining bytes from the buffer to the temp file. A similar bug occurred if sponge's input was empty. Amazing how such a seemingly simple thing can get so tricky.. Also added check for read error from the temp file, just in case. --- diff --git a/sponge.c b/sponge.c index 4a56222..948edf0 100644 --- a/sponge.c +++ b/sponge.c @@ -206,11 +206,14 @@ static void copy_tmpfile(FILE *tmpfile, FILE *outfd) { fclose(tmpfile); exit(1); } - // XXX I'd catch signals or writes errors here, but I - // I don't think it matters as the file is overwritten - while(fread(buf, BUFF_SIZE, 1, tmpfile) == 1) { + while (fread(buf, BUFF_SIZE, 1, tmpfile) > 0) { write_buff_out(buf, BUFF_SIZE, outfd); } + if (ferror(tmpfile)) { + perror("read temporary file"); + fclose(tmpfile); + exit(1); + } fclose(tmpfile); fclose(outfd); } @@ -274,7 +277,8 @@ int main (int argc, char **argv) { } if (tmpfile) { /* write whatever we have in memory to tmpfile */ - write_buff_tmp(bufstart, bufused, tmpfile); + if (bufused) + write_buff_tmp(bufstart, bufused, tmpfile); struct stat statbuf; if (outname && !stat(outname, &statbuf)) { /* regular file */ @@ -306,7 +310,8 @@ int main (int argc, char **argv) { exit(1); } } - write_buff_out(bufstart, bufused, outfd); + if (bufused) + write_buff_out(bufstart, bufused, outfd); fclose(outfd); }