open.c revision 302408
1/* open.c: The __opieopen() library function.
2
3%%% copyright-cmetz-96
4This software is Copyright 1996-2001 by Craig Metz, All Rights Reserved.
5The Inner Net License Version 3 applies to this software.
6You should have received a copy of the license with this software. If
7you didn't get a copy, you may request one from <license@inner.net>.
8
9	History:
10
11	Modified by cmetz for OPIE 2.4. More portable way to get the mode
12		string for fopen.
13	Created by cmetz for OPIE 2.3.
14*/
15#include "opie_cfg.h"
16
17#include <stdio.h>
18#include <sys/types.h>
19#if HAVE_UNISTD_H
20#include <unistd.h>
21#endif /* HAVE_UNISTD_H */
22#include <sys/stat.h>
23#include <errno.h>
24
25#include "opie.h"
26
27#if !HAVE_LSTAT
28#define lstat(x, y) stat(x, y)
29#endif /* !HAVE_LSTAT */
30
31FILE *__opieopen FUNCTION((file, rw, mode), char *file AND int rw AND int mode)
32{
33  FILE *f;
34  struct stat st;
35
36  if (lstat(file, &st)) {
37    if (errno != ENOENT)
38      return NULL;
39
40    if (!(f = fopen(file, "w")))
41      return NULL;
42
43    fclose(f);
44
45    if (chmod(file, mode))
46      return NULL;
47
48    if (lstat(file, &st))
49      return NULL;
50  }
51
52  if (!S_ISREG(st.st_mode))
53    return NULL;
54
55  {
56    char *fmode;
57
58    switch(rw) {
59      case 0:
60	fmode = "r";
61	break;
62      case 1:
63	fmode = "r+";
64	break;
65      case 2:
66	fmode = "a";
67	break;
68      default:
69	return NULL;
70    };
71
72    if (!(f = fopen(file, fmode)))
73      return NULL;
74  }
75
76  return f;
77}
78