fdgetc.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /* -*-comment-start: "//";comment-end:""-*-
  2. * GNU Mes --- Maxwell Equations of Software
  3. * Copyright © 2016,2017,2018,2019 Jan (janneke) Nieuwenhuizen <janneke@gnu.org>
  4. *
  5. * This file is part of GNU Mes.
  6. *
  7. * GNU Mes is free software; you can redistribute it and/or modify it
  8. * under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 3 of the License, or (at
  10. * your option) any later version.
  11. *
  12. * GNU Mes is distributed in the hope that it will be useful, but
  13. * WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with GNU Mes. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. #include <mes/lib.h>
  21. #include <errno.h>
  22. #include <limits.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include <sys/resource.h>
  26. #include <unistd.h>
  27. int errno;
  28. int *__ungetc_buf;
  29. int
  30. __ungetc_p (int filedes)
  31. {
  32. if (__ungetc_buf == 0)
  33. __ungetc_init ();
  34. return __ungetc_buf[filedes] >= 0;
  35. }
  36. void
  37. __ungetc_init ()
  38. {
  39. if (__ungetc_buf == 0)
  40. {
  41. int save_errno = errno;
  42. __ungetc_buf = malloc ((__FILEDES_MAX + 1) * sizeof (int));
  43. errno = save_errno;
  44. memset (__ungetc_buf, -1, (__FILEDES_MAX + 1) * sizeof (int));
  45. }
  46. }
  47. void
  48. __ungetc_clear (int filedes)
  49. {
  50. if (__ungetc_buf == 0)
  51. __ungetc_init ();
  52. __ungetc_buf[filedes] = -1;
  53. }
  54. void
  55. __ungetc_set (int filedes, int c)
  56. {
  57. if (__ungetc_buf == 0)
  58. __ungetc_init ();
  59. __ungetc_buf[filedes] = c;
  60. }
  61. int
  62. fdgetc (int fd)
  63. {
  64. if (__ungetc_buf == 0)
  65. __ungetc_init ();
  66. char c;
  67. int i = __ungetc_buf[fd];
  68. if (i >= 0)
  69. __ungetc_buf[fd] = -1;
  70. else
  71. {
  72. int r = read (fd, &c, 1);
  73. if (r < 1)
  74. return -1;
  75. i = c;
  76. }
  77. if (i < 0)
  78. i = i + 256;
  79. return i;
  80. }