1 /* 2 * pANS stdio -- freopen 3 */ 4 #include "iolib.h" 5 /* 6 * Open the named file with the given mode, using the given FILE 7 * Legal modes are given below, `additional characters may follow these sequences': 8 * r rb open to read 9 * w wb open to write, truncating 10 * a ab open to write positioned at eof, creating if non-existant 11 * r+ r+b rb+ open to read and write, creating if non-existant 12 * w+ w+b wb+ open to read and write, truncating 13 * a+ a+b ab+ open to read and write, positioned at eof, creating if non-existant. 14 */ 15 FILE *freopen(const char *name, const char *mode, FILE *f){ 16 int m; 17 18 if(f->state!=CLOSED){ 19 fclose(f); 20 f->state=OPEN; 21 } 22 23 m = *mode++; 24 if(m == 0) 25 return NULL; 26 if(*mode == 'b') 27 mode++; 28 switch(m){ 29 default: 30 return NULL; 31 case 'r': 32 m = 0; 33 if(*mode == '+') m = 2; 34 f->fd=open(name, m); 35 break; 36 case 'w': 37 m = 1; 38 if(*mode == '+') m = 2; 39 f->fd=create(name, m, 0666); 40 break; 41 case 'a': 42 m = 1; 43 if(*mode == '+') m = 2; 44 f->fd=open(name, m); 45 if(f->fd<0) 46 f->fd=create(name, m, 0666); 47 seek(f->fd, 0L, 2); 48 break; 49 } 50 51 if(f->fd==-1) 52 return NULL; 53 f->flags=(mode[0]=='a')? APPEND : 0; 54 f->state=OPEN; 55 f->buf=0; 56 f->rp=0; 57 f->wp=0; 58 f->lp=0; 59 return f; 60 } 61