freopen.c 1.2 KB

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