fopen.c 590 B

12345678910111213141516171819202122232425262728293031
  1. #include "stdio_impl.h"
  2. #include <fcntl.h>
  3. #include <string.h>
  4. #include <errno.h>
  5. FILE *fopen(const char *restrict filename, const char *restrict mode)
  6. {
  7. FILE *f;
  8. int fd;
  9. int flags;
  10. /* Check for valid initial mode character */
  11. if (!strchr("rwa", *mode)) {
  12. errno = EINVAL;
  13. return 0;
  14. }
  15. /* Compute the flags to pass to open() */
  16. flags = __fmodeflags(mode);
  17. fd = sys_open(filename, flags, 0666);
  18. if (fd < 0) return 0;
  19. if (flags & O_CLOEXEC)
  20. __syscall(SYS_fcntl, fd, F_SETFD, FD_CLOEXEC);
  21. f = __fdopen(fd, mode);
  22. if (f) return f;
  23. __syscall(SYS_close, fd);
  24. return 0;
  25. }