fread.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* -*-comment-start: "//";comment-end:""-*-
  2. * GNU Mes --- Maxwell Equations of Software
  3. * Copyright © 2017,2018 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 <stdio.h>
  22. #include <string.h>
  23. #include <unistd.h>
  24. int
  25. __fungetc_p (FILE * stream)
  26. {
  27. return __ungetc_p ((int) (long) stream);
  28. }
  29. size_t
  30. fread (void *data, size_t size, size_t count, FILE * stream)
  31. {
  32. if (!size || !count)
  33. return 0;
  34. size_t todo = size * count;
  35. char *buf = (char *) data;
  36. int bytes = 0;
  37. while (__fungetc_p (stream) && todo-- && ++bytes)
  38. *buf++ = fgetc (stream);
  39. int filedes = (long) stream;
  40. if (todo)
  41. {
  42. int r = read (filedes, buf, todo);
  43. if (r < 0 && !bytes)
  44. bytes = r;
  45. else
  46. bytes += r;
  47. }
  48. if (__mes_debug ())
  49. {
  50. static char debug_buf[4096];
  51. eputs ("fread fd=");
  52. eputs (itoa (filedes));
  53. eputs (" bytes=");
  54. eputs (itoa (bytes));
  55. eputs ("\n");
  56. if (bytes > 0 && bytes < sizeof (debug_buf))
  57. {
  58. strncpy (debug_buf, data, bytes);
  59. buf[bytes] = 0;
  60. eputs ("fread buf=");
  61. eputs (debug_buf);
  62. eputs ("\n");
  63. }
  64. }
  65. if (bytes > 0)
  66. return bytes / size;
  67. return 0;
  68. }