setvbuf.c 879 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * setbuf.c - control buffering of a stream
  3. */
  4. /* $Id$ */
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include "loc_incl.h"
  8. extern void (*_clean)(void);
  9. int
  10. setvbuf(register FILE *stream, char *buf, int mode, size_t size)
  11. {
  12. int retval = 0;
  13. _clean = __cleanup;
  14. if (mode != _IOFBF && mode != _IOLBF && mode != _IONBF)
  15. return EOF;
  16. if (stream->_buf && io_testflag(stream,_IOMYBUF) )
  17. free((void *)stream->_buf);
  18. stream->_flags &= ~(_IOMYBUF | _IONBF | _IOLBF);
  19. if (buf && size <= 0) retval = EOF;
  20. if (!buf && (mode != _IONBF)) {
  21. if (size <= 0 || (buf = (char *) malloc(size)) == NULL) {
  22. retval = EOF;
  23. } else {
  24. stream->_flags |= _IOMYBUF;
  25. }
  26. }
  27. stream->_buf = (unsigned char *) buf;
  28. stream->_count = 0;
  29. stream->_flags |= mode;
  30. stream->_ptr = stream->_buf;
  31. if (!buf) {
  32. stream->_bufsiz = 1;
  33. } else {
  34. stream->_bufsiz = size;
  35. }
  36. return retval;
  37. }