commit c0d36e0064f22738982d11cedb910f027aae3cf6
parent 124cb7415a9a1a55f2dff5adc36a2e14f0392adc
Author: sin <sin@2f30.org>
Date: Mon, 9 Feb 2015 15:22:03 +0000
Switch concat() to use fread() and fwrite()
We should never mix FILE I/O with raw I/O. Going from raw I/O
to FILE I/O is fine but doing the opposite is extremely tricky and
only works under certain conditions (unbuffered stream + no call
to ungetc()).
Diffstat:
1 file changed, 6 insertions(+), 5 deletions(-)
diff --git a/libutil/concat.c b/libutil/concat.c
@@ -1,6 +1,5 @@
/* See LICENSE file for copyright and license details. */
#include <stdio.h>
-#include <unistd.h>
#include "../text.h"
#include "../util.h"
@@ -9,12 +8,14 @@ void
concat(FILE *fp1, const char *s1, FILE *fp2, const char *s2)
{
char buf[BUFSIZ];
- ssize_t n;
+ size_t n;
- while ((n = read(fileno(fp1), buf, sizeof buf)) > 0) {
- if (write(fileno(fp2), buf, n) != n)
+ while ((n = fread(buf, 1, sizeof(buf), fp1)) > 0) {
+ if (fwrite(buf, 1, n, fp2) != n)
eprintf("%s: write error:", s2);
+ if (feof(fp1))
+ break;
}
- if (n < 0)
+ if (ferror(fp1))
eprintf("%s: read error:", s1);
}