1 #include <errno.h>
2 #include <stdarg.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <string.h>
6 #include "lib.h"
7 #include <sys/stat.h>
8 #include "sys9.h"
9
10 /*
11 * O_NOCTTY has no effect
12 */
13 int
open(const char * path,int flags,...)14 open(const char *path, int flags, ...)
15 {
16 int n;
17 long f;
18 int mode;
19 Fdinfo *fi;
20 va_list va;
21
22 f = flags&O_ACCMODE;
23 if(flags&O_CREAT){
24 if(access(path, 0) >= 0){
25 if(flags&O_EXCL){
26 errno = EEXIST;
27 return -1;
28 }else{
29 if((flags&O_TRUNC)&&(flags&(O_RDWR|O_WRONLY)))
30 f |= 16;
31 n = _OPEN(path, f);
32 }
33 }else{
34 va_start(va, flags);
35 mode = va_arg(va, int);
36 va_end(va);
37 n = _CREATE(path, f, mode&0777);
38 }
39 if(n < 0)
40 _syserrno();
41 }else{
42 if((flags&O_TRUNC)&&(flags&(O_RDWR|O_WRONLY)))
43 f |= 16;
44 n = _OPEN(path, f);
45 if(n < 0)
46 _syserrno();
47 }
48 if(n >= 0){
49 fi = &_fdinfo[n];
50 fi->flags = FD_ISOPEN;
51 fi->oflags = flags&(O_ACCMODE|O_NONBLOCK|O_APPEND);
52 fi->uid = -2;
53 fi->gid = -2;
54 fi->name = malloc(strlen(path)+1);
55 if(fi->name)
56 strcpy(fi->name, path);
57 if(fi->oflags&O_APPEND)
58 _SEEK(n, 0, 2);
59 }
60 return n;
61 }
62