1#include <errno.h>2#include <stdio.h>3#include <stdlib.h>45#include "../libc.h"67#undef setvbuf89int10setvbuf(FILE *restrict fp, char *restrict buf, int mode, size_t size)11{12 int flags;13 unsigned char *p;14 size_t l;1516 if (_flsbuf(fp) == EOF)17 return EOF;1819 if (buf)20 p = (unsigned char *) buf, l = size;21 else22 p = fp->buf, l = fp->len;2324 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 }3738 flags = fp->flags;39 if (flags&_IOALLOC && (buf || mode == _IONBF)) {40 free(fp->buf);41 flags &= ~_IOALLOC;42 }4344 fp->buf = p;45 fp->len = l;46 flags &= ~(_IONBF | _IOLBF | _IOFBF);47 flags |= mode;48 fp->flags = flags;4950 return 0;51}