scc

simple c99 compiler
git clone git://git.simple-cc.org/scc
Log | Files | Refs | Submodules | README | LICENSE

setvbuf.c (767B)


      1 #include <errno.h>
      2 #include <stdio.h>
      3 #include <stdlib.h>
      4 
      5 #include "../libc.h"
      6 
      7 #undef setvbuf
      8 
      9 int
     10 setvbuf(FILE *restrict fp, char *restrict buf, int mode, size_t size)
     11 {
     12 	int flags;
     13 	unsigned char *p;
     14 	size_t l;
     15 
     16 	if (_flsbuf(fp) == EOF)
     17 		return EOF;
     18 
     19 	if (buf)
     20 		p = (unsigned char *) buf, l = size;
     21 	else
     22 		p = fp->buf, l = fp->len;
     23 
     24 	switch (mode) {
     25 	case _IONBF:
     26 		l = sizeof(fp->unbuf);
     27 		p = fp->unbuf;
     28 	case _IOLBF:
     29 	case _IOFBF:
     30 		fp->rp = fp->wp = p;
     31 		fp->lp = p + l;
     32 		break;
     33 	default:
     34 		errno = EINVAL;
     35 		return EOF;
     36 	}
     37 
     38 	flags = fp->flags;
     39 	if (flags&_IOALLOC && (buf || mode == _IONBF)) {
     40 		free(fp->buf);
     41 		flags &= ~_IOALLOC;
     42 	}
     43 
     44 	fp->buf = p;
     45 	fp->len = l;
     46 	flags &= ~(_IONBF | _IOLBF | _IOFBF);
     47 	flags |= mode;
     48 	fp->flags = flags;
     49 
     50 	return 0;
     51 }