fopen.c - vx32 - Local 9vx git repository for patches.
(HTM) git clone git://r-36.net/vx32
(DIR) Log
(DIR) Files
(DIR) Refs
---
fopen.c (1154B)
---
1 #include <stdio.h>
2 #include <string.h>
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <unistd.h>
6 #include <stdlib.h>
7 #include "ioprivate.h"
8
9 FILE *fopen(const char *name, const char *mode)
10 {
11 int fd, umode, seek, append;
12 FILE *f;
13
14 umode = 0;
15 seek = 0;
16 append = 0;
17 if (mode[0] == 'r' && mode[1] == '+') {
18 umode = O_RDWR;
19 } else if (mode[0] == 'r') {
20 umode = O_RDONLY;
21 } else if (mode[0] == 'w' && mode[1] == '+') {
22 umode = O_RDWR|O_CREAT|O_TRUNC;
23 } else if (mode[0] == 'w') {
24 umode = O_WRONLY|O_CREAT|O_TRUNC;
25 } else if (mode[0] == 'a' && mode[1] == '+') {
26 umode = O_RDWR|O_CREAT;
27 append = 1;
28 } else if (mode[0] == 'a') {
29 umode = O_WRONLY|O_CREAT;
30 seek = 1;
31 } else {
32 errno = EINVAL;
33 return NULL;
34 }
35
36 f = malloc(sizeof *f);
37 if (f == NULL)
38 return NULL;
39 memset(f, 0, sizeof *f);
40 f->ibuf = malloc(BUFSIZ);
41 f->obuf = malloc(BUFSIZ);
42 if (f->ibuf == NULL || f->obuf == NULL) {
43 freef:
44 free(f->ibuf);
45 free(f->obuf);
46 free(f);
47 return NULL;
48 }
49 f->imax = BUFSIZ;
50 f->omax = BUFSIZ;
51
52 if ((fd = open(name, umode, 0666)) < 0)
53 goto freef;
54
55 if (seek)
56 lseek(fd, 0, 2);
57 f->append = append;
58 f->fd = fd;
59 return f;
60 }