fillbuf.c 1.4 KB

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