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 if(f->state!=CLOSED) fclose(f); 17 if(mode[1]=='+' || mode[2]=='+'){ 18 if(mode[0]=='w') f->fd=create(name, 2, 0666); 19 else{ 20 f->fd=open(name, 2); 21 if(mode[0]=='a'){ 22 if(f->fd<0) 23 f->fd=create(name, 2, 0666); 24 if(f->fd>=0) 25 seek(f->fd, 0L, 2); 26 } 27 } 28 } 29 else{ 30 switch(mode[0]){ 31 default: return NULL; 32 case 'r': 33 f->fd=open(name, 0); 34 break; 35 case 'w': 36 f->fd=create(name, 1, 0666); 37 break; 38 case 'a': 39 f->fd=open(name, 1); 40 if(f->fd==-1) 41 f->fd=create(name, 1, 0666); 42 seek(f->fd, 0L, 2); 43 break; 44 } 45 } 46 if(f->fd==-1) return NULL; 47 f->flags=(mode[0]=='a')? APPEND : 0; 48 f->state=OPEN; 49 f->buf=0; 50 f->rp=0; 51 f->wp=0; 52 f->lp=0; 53 return f; 54 } 55