fseek.c 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #include "stdio_impl.h"
  2. #include <errno.h>
  3. int __fseeko_unlocked(FILE *f, off_t off, int whence)
  4. {
  5. /* Fail immediately for invalid whence argument. */
  6. if (whence != SEEK_CUR && whence != SEEK_SET && whence != SEEK_END) {
  7. errno = EINVAL;
  8. return -1;
  9. }
  10. /* Adjust relative offset for unread data in buffer, if any. */
  11. if (whence == SEEK_CUR && f->rend) off -= f->rend - f->rpos;
  12. /* Flush write buffer, and report error on failure. */
  13. if (f->wpos != f->wbase) {
  14. f->write(f, 0, 0);
  15. if (!f->wpos) return -1;
  16. }
  17. /* Leave writing mode */
  18. f->wpos = f->wbase = f->wend = 0;
  19. /* Perform the underlying seek. */
  20. if (f->seek(f, off, whence) < 0) return -1;
  21. /* If seek succeeded, file is seekable and we discard read buffer. */
  22. f->rpos = f->rend = 0;
  23. f->flags &= ~F_EOF;
  24. return 0;
  25. }
  26. int __fseeko(FILE *f, off_t off, int whence)
  27. {
  28. int result;
  29. FLOCK(f);
  30. result = __fseeko_unlocked(f, off, whence);
  31. FUNLOCK(f);
  32. return result;
  33. }
  34. int fseek(FILE *f, long off, int whence)
  35. {
  36. return __fseeko(f, off, whence);
  37. }
  38. weak_alias(__fseeko, fseeko);