seek.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 <grass/config.h>
  14. #include <stdio.h>
  15. #include <sys/types.h>
  16. #include <unistd.h>
  17. #include <string.h>
  18. #include <errno.h>
  19. #include <grass/gis.h>
  20. #include <grass/segment.h>
  21. /**
  22. * \fn int segment_seek (SEGMENT *SEG, int n, int index)
  23. *
  24. * \brief Seek into a segment.
  25. *
  26. * \param[in,out] SEG segment
  27. * \param[in] n
  28. * \param[in] index
  29. * \return 0 on success
  30. * \return -1 if unable to seek
  31. */
  32. int segment_seek_fast(const SEGMENT * SEG, int n, int index)
  33. {
  34. off_t offset = (((off_t) n) << SEG->sizebits) + index + SEG->offset;
  35. if (lseek(SEG->fd, offset, SEEK_SET) == (off_t) - 1) {
  36. G_warning("segment_seek: %s", strerror(errno));
  37. return -1;
  38. }
  39. return 0;
  40. }
  41. int segment_seek_slow(const SEGMENT * SEG, int n, int index)
  42. {
  43. off_t offset;
  44. offset = (off_t) n * SEG->size + index + SEG->offset;
  45. if (lseek(SEG->fd, offset, SEEK_SET) == (off_t) - 1) {
  46. G_warning("segment_seek: %s", strerror(errno));
  47. return -1;
  48. }
  49. return 0;
  50. }
  51. static int (*segment_seek_mode[2]) () = {
  52. segment_seek_fast, segment_seek_slow};
  53. int segment_seek(const SEGMENT * SEG, int n, int index)
  54. {
  55. return (*segment_seek_mode[SEG->slow_seek]) (SEG, n, index);
  56. }