summaryrefslogtreecommitdiff
path: root/src/libstddjb/fd_catn.c
blob: 4f1016ea0dd1065d0b7b7d1c0458178dd79055fa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* ISC license. */

#include <unistd.h>
#include <errno.h>

#include <skalibs/allreadwrite.h>
#include <skalibs/djbunix.h>

#define BSIZE 65536

off_t fd_catn (int from, int to, off_t n)
{
  off_t w = 0 ;
  char buf[BSIZE] ;
  while (n >= BSIZE)
  {
    size_t v ;
    ssize_t r = fd_read(from, buf, BSIZE) ;
    if (r == -1) return w ;
    if (!r) return (errno = EPIPE, w) ;
    v = allwrite(to, buf, r) ;
    if (v < r) return w + v ;
    n -= r ; w += r ;
  }

  if (n)
  {
    size_t r = allread(from, buf, n) ;
    size_t v = 0 ;
    if (r) v = allwrite(to, buf, r) ;
    w += v ;
  }
  return w ;
}