-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path_fopen.c
78 lines (66 loc) · 1.98 KB
/
_fopen.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#ifndef mini__fopen_c
#define mini__fopen_c
#include "include/filemodes.h"
int volatile open( const char *s, int flags, ... );
//+header stdio.h
//+depends open fileno close
//+needs lseek.h
//+doc modes implemented: r, r+, w, w+, a, a+
//+def
FILE *_fopen(int fd, const char* filename, const char* mode, FILE *f){
int imode;
switch (mode[0]){
case 'r': imode = O_RDONLY;
break;
case 'w': imode = O_WRONLY | O_TRUNC | O_CREAT;
break;
case 'a': imode = O_APPEND | O_RDWR; // somehow only "a+" works. Not sure, why.
break;
default: return((FILE*)0); // hopefully a fd cannot be 0.? By reading the manual,
// I conclude only stdin has the fildes 0. So It MIGHT be ok.
// Anyways, if someone's trying to open stdin via fopen and is wondering, what's going on..
// Here's the answer. But, regarding the bsd manuals, one shouldn't open stdin with fopen at all. so..
}
for ( int a=1; (mode[a] != 0) && ( a<6 ); a++ ){
if ( mode[a] == '+' ){
imode = ( ( imode | O_RDWR ) & ~( O_WRONLY | O_RDONLY) );
} else {
#if 0
//printf("XXX: %c", mode[a]);
switch (mode[0]){
case 'r': //imode = O_RDONLY;
break;
case 'w': if ( mode[a] == 'x' )
imode = imode & ( ~(O_CREAT | O_TRUNC) );
break;
case 'a': //imode = O_APPEND | O_RDWR;
break;
}
#endif
}
}
if ( f == 0 ){
int a;
if ( mlgl->pstream >= mini_FOPEN_MAX){ // Too many opened streams. Look for an empty storage location
for ( a=3; mlgl->stream[a]>=0; a++ )
if ( a >= mini_FOPEN_MAX ) //
return(0);
} else {
a = mlgl->pstream;
mlgl->pstream++;
}
//printf("a: %d\n",a);
f = &mlgl->stream[a];
} else { // freopen - error handling?
close(fileno(f));
}
if ( filename != 0 )
*f = open( filename, imode, 0666 );
else
*f = fd;
//if ( *f == -1 )
if ( *f < 0 )
return(0);
return ( f ); //
}
#endif