open.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include <errno.h>
  2. #include <stdarg.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <string.h>
  6. #include "lib.h"
  7. #include <sys/stat.h>
  8. #include "sys9.h"
  9. /*
  10. * O_NOCTTY has no effect
  11. */
  12. int
  13. open(const char *path, int flags, ...)
  14. {
  15. int n;
  16. long f;
  17. int mode;
  18. Fdinfo *fi;
  19. va_list va;
  20. struct stat sbuf;
  21. f = flags&O_ACCMODE;
  22. if(flags&O_CREAT){
  23. if(access(path, 0) >= 0){
  24. if(flags&O_EXCL){
  25. errno = EEXIST;
  26. return -1;
  27. }else{
  28. if((flags&O_TRUNC)&&(flags&(O_RDWR|O_WRONLY)))
  29. f |= 16;
  30. n = _OPEN(path, f);
  31. }
  32. }else{
  33. va_start(va, flags);
  34. mode = va_arg(va, int);
  35. va_end(va);
  36. n = _CREATE(path, f, mode&0777);
  37. }
  38. if(n < 0)
  39. _syserrno();
  40. }else{
  41. if((flags&O_TRUNC)&&(flags&(O_RDWR|O_WRONLY)))
  42. f |= 16;
  43. n = _OPEN(path, f);
  44. if(n < 0)
  45. _syserrno();
  46. }
  47. if(n >= 0){
  48. fi = &_fdinfo[n];
  49. fi->flags = FD_ISOPEN;
  50. fi->oflags = flags&(O_ACCMODE|O_NONBLOCK|O_APPEND);
  51. fi->uid = -2;
  52. fi->gid = -2;
  53. fi->name = malloc(strlen(path)+1);
  54. if(fi->name)
  55. strcpy(fi->name, path);
  56. if(fi->oflags&O_APPEND)
  57. _SEEK(n, 0, 2);
  58. }
  59. return n;
  60. }