fillbuf.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * fillbuf.c - fill a buffer
  3. */
  4. /* $Header$ */
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include "loc_incl.h"
  8. int read(int d, char *buf, int nbytes);
  9. int
  10. __fillbuf(register FILE *stream)
  11. {
  12. static unsigned char ch[FOPEN_MAX];
  13. stream->_count = 0;
  14. if (fileno(stream) < 0) return EOF;
  15. if (io_testflag(stream, (_IOEOF | _IOERR ))) return EOF;
  16. if (!io_testflag(stream, _IOREAD)) return EOF;
  17. if (io_testflag(stream, _IOWRITING)) return EOF;
  18. if (!io_testflag(stream, _IOREADING))
  19. stream->_flags |= _IOREADING;
  20. if (!io_testflag(stream, _IONBF) && !stream->_buf) {
  21. stream->_buf = (unsigned char *) malloc(BUFSIZ);
  22. if (!stream->_buf) {
  23. stream->_flags |= _IONBF;
  24. }
  25. else {
  26. stream->_flags |= _IOMYBUF;
  27. stream->_bufsiz = BUFSIZ;
  28. }
  29. }
  30. if (io_testflag(stream, _IONBF | _IOLBF)) {
  31. register int i;
  32. for (i = 0; i < FOPEN_MAX; i++) {
  33. if (__iotab[i] && io_testflag(__iotab[i], _IOLBF))
  34. if (io_testflag(__iotab[i], _IOWRITING))
  35. (void) fflush(__iotab[i]);
  36. }
  37. }
  38. if (!stream->_buf) {
  39. stream->_buf = &ch[fileno(stream)];
  40. stream->_bufsiz = 1;
  41. }
  42. stream->_ptr = stream->_buf;
  43. stream->_count = read(stream->_fd, (char *)stream->_buf, stream->_bufsiz);
  44. if (stream->_count <= 0){
  45. if (stream->_count == 0) {
  46. stream->_flags |= _IOEOF;
  47. }
  48. else
  49. stream->_flags |= _IOERR;
  50. return EOF;
  51. }
  52. stream->_count--;
  53. return *stream->_ptr++;
  54. }