fdopen.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. * Posix stdio -- fdopen
  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 *fdopen(const int fd, const char *mode){
  24. FILE *f;
  25. qlock(&_stdiolk);
  26. for(f=_IO_stream;f!=&_IO_stream[FOPEN_MAX];f++)
  27. if(f->state==CLOSED)
  28. break;
  29. if(f==&_IO_stream[FOPEN_MAX]) {
  30. qunlock(&_stdiolk);
  31. return NULL;
  32. }
  33. f->fd=fd;
  34. if(mode[0]=='a')
  35. seek(f->fd, 0L, 2);
  36. if(f->fd==-1) return NULL;
  37. f->flags=0;
  38. f->state=OPEN;
  39. f->buf=0;
  40. f->rp=0;
  41. f->wp=0;
  42. f->lp=0;
  43. qunlock(&_stdiolk);
  44. return f;
  45. }