concat: Use plain read/write instead of buffered stdio

If we are just copying data from one file to another, we don't need to
fill a complete buffer, just read a chunk at a time, and write it to the
output.
This commit is contained in:
Michael Forney
2017-07-03 14:58:49 -07:00
committed by Anselm R Garbe
parent 9a3b12525b
commit 3276fbea1c
8 changed files with 202 additions and 171 deletions

View File

@@ -1,19 +1,23 @@
/* See LICENSE file for copyright and license details. */
#include <stdio.h>
#include <unistd.h>
#include "../text.h"
#include "../util.h"
void
concat(FILE *fp1, const char *s1, FILE *fp2, const char *s2)
int
concat(int f1, const char *s1, int f2, const char *s2)
{
char buf[BUFSIZ];
size_t n;
ssize_t n;
while ((n = fread(buf, 1, sizeof(buf), fp1))) {
fwrite(buf, 1, n, fp2);
if (feof(fp1) || ferror(fp1) || ferror(fp2))
break;
while ((n = read(f1, buf, sizeof(buf))) > 0) {
if (writeall(f2, buf, n) < 0) {
weprintf("write %s:", s2);
return -2;
}
}
if (n < 0) {
weprintf("read %s:", s1);
return -1;
}
return 0;
}