fopen.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /* -*-comment-start: "//";comment-end:""-*-
  2. * GNU Mes --- Maxwell Equations of Software
  3. * Copyright © 2017,2018,2019 Jan (janneke) Nieuwenhuizen <janneke@gnu.org>
  4. * Copyright © 2018 Jeremiah Orians <jeremiah@pdp10.guru>
  5. *
  6. * This file is part of GNU Mes.
  7. *
  8. * GNU Mes is free software; you can redistribute it and/or modify it
  9. * under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 3 of the License, or (at
  11. * your option) any later version.
  12. *
  13. * GNU Mes is distributed in the hope that it will be useful, but
  14. * WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with GNU Mes. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. #include <mes/lib.h>
  22. #include <assert.h>
  23. #include <fcntl.h>
  24. #include <stdio.h>
  25. #include <string.h>
  26. #include <unistd.h>
  27. FILE *
  28. fopen (char const *file_name, char const *opentype)
  29. {
  30. if (__mes_debug ())
  31. {
  32. eputs ("fopen ");
  33. eputs (file_name);
  34. eputs (" ");
  35. eputs (opentype);
  36. eputs ("\n");
  37. }
  38. int fd;
  39. int mode = 0600;
  40. if ((opentype[0] == 'a' || !strcmp (opentype, "r+")) && !access (file_name, O_RDONLY))
  41. {
  42. int flags = O_RDWR;
  43. if (opentype[0] == 'a')
  44. flags |= O_APPEND;
  45. fd = _open3 (file_name, flags, mode);
  46. }
  47. else if (opentype[0] == 'w' || opentype[0] == 'a' || !strcmp (opentype, "r+"))
  48. {
  49. char *plus_p = strchr (opentype, '+');
  50. int flags = plus_p ? O_RDWR | O_CREAT : O_WRONLY | O_CREAT | O_TRUNC;
  51. fd = _open3 (file_name, flags, mode);
  52. }
  53. else
  54. fd = _open3 (file_name, O_RDONLY, 0);
  55. if (__mes_debug ())
  56. {
  57. eputs (" => fd=");
  58. eputs (itoa (fd));
  59. eputs ("\n");
  60. }
  61. if (!fd)
  62. {
  63. eputs (" ***MES LIB C*** fopen of stdin: signal me in band\n");
  64. assert (0);
  65. }
  66. if (fd < 0)
  67. fd = 0;
  68. return (FILE *) (long) fd;
  69. }