seek.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * \file seek.c
  3. *
  4. * \brief Segment seek routines.
  5. *
  6. * This program is free software under the GNU General Public License
  7. * (>=v2). Read the file COPYING that comes with GRASS for details.
  8. *
  9. * \author GRASS GIS Development Team
  10. *
  11. * \date 2005-2009
  12. */
  13. #include <stdio.h>
  14. #include <sys/types.h>
  15. #include <unistd.h>
  16. #include <string.h>
  17. #include <errno.h>
  18. #include <grass/gis.h>
  19. #include <grass/segment.h>
  20. /**
  21. * \fn int segment_seek (SEGMENT *SEG, int n, int index)
  22. *
  23. * \brief Seek into a segment.
  24. *
  25. * \param[in,out] SEG segment
  26. * \param[in] n
  27. * \param[in] index
  28. * \return 0 on success
  29. * \return -1 if unable to seek
  30. */
  31. int segment_seek_fast(const SEGMENT * SEG, int n, int index)
  32. {
  33. off_t offset = (((off_t) n) << SEG->sizebits) + index + SEG->offset;
  34. if (lseek(SEG->fd, offset, SEEK_SET) == (off_t) - 1) {
  35. G_warning("segment_seek: %s", strerror(errno));
  36. return -1;
  37. }
  38. return 0;
  39. }
  40. int segment_seek_slow(const SEGMENT * SEG, int n, int index)
  41. {
  42. off_t offset = (off_t) n * SEG->size + index + SEG->offset;
  43. if (lseek(SEG->fd, offset, SEEK_SET) == (off_t) - 1) {
  44. G_warning("segment_seek: %s", strerror(errno));
  45. return -1;
  46. }
  47. return 0;
  48. }
  49. static int (*segment_seek_mode[2]) () = {
  50. segment_seek_fast, segment_seek_slow};
  51. int segment_seek(const SEGMENT * SEG, int n, int index)
  52. {
  53. return (*segment_seek_mode[SEG->slow_seek]) (SEG, n, index);
  54. }