boot2

Playing with the boostrap
git clone https://git.ryansepassi.com/git/boot2.git
Log | Files | Refs | README

fopen.c (2066B)


      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 
     22 #include <mes/lib.h>
     23 #include <assert.h>
     24 #include <fcntl.h>
     25 #include <stdio.h>
     26 #include <string.h>
     27 #include <unistd.h>
     28 
     29 FILE *
     30 fopen (char const *file_name, char const *opentype)
     31 {
     32   if (__mes_debug ())
     33     {
     34       eputs ("fopen ");
     35       eputs (file_name);
     36       eputs (" ");
     37       eputs (opentype);
     38       eputs ("\n");
     39     }
     40 
     41   int fd;
     42   int mode = 0600;
     43   if ((opentype[0] == 'a' || !strcmp (opentype, "r+")) && !access (file_name, O_RDONLY))
     44     {
     45       int flags = O_RDWR;
     46       if (opentype[0] == 'a')
     47         flags |= O_APPEND;
     48       fd = _open3 (file_name, flags, mode);
     49     }
     50   else if (opentype[0] == 'w' || opentype[0] == 'a' || !strcmp (opentype, "r+"))
     51     {
     52       char *plus_p = strchr (opentype, '+');
     53       int flags = plus_p ? O_RDWR | O_CREAT : O_WRONLY | O_CREAT | O_TRUNC;
     54       fd = _open3 (file_name, flags, mode);
     55     }
     56   else
     57     fd = _open3 (file_name, O_RDONLY, 0);
     58 
     59   if (__mes_debug ())
     60     {
     61       eputs (" => fd=");
     62       eputs (itoa (fd));
     63       eputs ("\n");
     64     }
     65 
     66   if (!fd)
     67     {
     68       eputs (" ***MES LIB C*** fopen of stdin: signal me in band\n");
     69       assert (0);
     70     }
     71   if (fd < 0)
     72     fd = 0;
     73   return (FILE *) (long) fd;
     74 }