freopen.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. /*
  10. * pANS stdio -- freopen
  11. */
  12. #include "iolib.h"
  13. /*
  14. * Open the named file with the given mode, using the given FILE
  15. * Legal modes are given below, `additional characters may follow these sequences':
  16. * r rb open to read
  17. * w wb open to write, truncating
  18. * a ab open to write positioned at eof, creating if non-existant
  19. * r+ r+b rb+ open to read and write, creating if non-existant
  20. * w+ w+b wb+ open to read and write, truncating
  21. * a+ a+b ab+ open to read and write, positioned at eof, creating if non-existant.
  22. */
  23. FILE *freopen(const char *name, const char *mode, FILE *f){
  24. int m;
  25. if(f->state!=CLOSED){
  26. fclose(f);
  27. /* premature; fall through and see what happens */
  28. /* f->state=OPEN; */
  29. }
  30. m = *mode++;
  31. if(m == 0)
  32. return NULL;
  33. if(*mode == 'b')
  34. mode++;
  35. switch(m){
  36. default:
  37. return NULL;
  38. case 'r':
  39. f->fd=open(name, (*mode == '+'? ORDWR: OREAD));
  40. break;
  41. case 'w':
  42. f->fd=create(name, (*mode == '+'? ORDWR: OWRITE), 0666);
  43. break;
  44. case 'a':
  45. m = (*mode == '+'? ORDWR: OWRITE);
  46. f->fd=open(name, m);
  47. if(f->fd<0)
  48. f->fd=create(name, m, 0666);
  49. seek(f->fd, 0LL, 2);
  50. break;
  51. }
  52. if(f->fd==-1)
  53. return NULL;
  54. f->flags=(mode[0]=='a')? APPEND : 0;
  55. f->state=OPEN;
  56. f->buf=0;
  57. f->rp=0;
  58. f->wp=0;
  59. f->lp=0;
  60. return f;
  61. }