get_row.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /**
  2. * \file lib/segment/get_row.c
  3. *
  4. * \brief Segment row retrieval 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-2018
  12. */
  13. #include <stdio.h>
  14. #include <unistd.h>
  15. #include <string.h>
  16. #include <errno.h>
  17. #include <grass/gis.h>
  18. #include "local_proto.h"
  19. /**
  20. * \fn int Segment_get_row (SEGMENT *SEG, void *buf, int row)
  21. *
  22. * \brief Read row from segment file.
  23. *
  24. * Transfers data from a segment file, row by row, into memory
  25. * (which can then be written to a regular matrix file). <b>Seg</b> is the
  26. * segment structure that was configured from a call to
  27. * <i>Segment_init()</i>.
  28. *
  29. * <b>Buf</b> will be filled with <em>ncols*len</em> bytes of data
  30. * corresponding to the <b>row</b> in the data matrix.
  31. *
  32. * \param[in] seg segment
  33. * \param[in,out] buf
  34. * \param[in] row
  35. * \return 1 if successful
  36. * \return -1 if unable to seek or read segment file
  37. */
  38. int Segment_get_row(const SEGMENT * SEG, void *buf, off_t row)
  39. {
  40. int size;
  41. off_t ncols, col;
  42. int scols;
  43. int n, index;
  44. if (SEG->cache) {
  45. memcpy(buf, SEG->cache + ((size_t)row * SEG->ncols) * SEG->len, SEG->len * SEG->ncols);
  46. return 1;
  47. }
  48. ncols = SEG->ncols - SEG->spill;
  49. scols = SEG->scols;
  50. size = scols * SEG->len;
  51. for (col = 0; col < ncols; col += scols) {
  52. SEG->address(SEG, row, col, &n, &index);
  53. SEG->seek(SEG, n, index);
  54. if (read(SEG->fd, buf, size) != size) {
  55. G_warning("Segment_get_row: %s", strerror(errno));
  56. return -1;
  57. }
  58. /* The buf variable is a void pointer and thus points to anything. */
  59. /* Therefore, it's size is unknown and thus, it cannot be used for */
  60. /* pointer arithmetic (some compilers treat this as an error - SGI */
  61. /* MIPSPro compiler for one). Since the read command is reading in */
  62. /* "size" bytes, cast the buf variable to char * before incrementing */
  63. buf = ((char *)buf) + size;
  64. }
  65. if ((size = SEG->spill * SEG->len)) {
  66. SEG->address(SEG, row, col, &n, &index);
  67. SEG->seek(SEG, n, index);
  68. if (read(SEG->fd, buf, size) != size) {
  69. G_warning("Segment_get_row: %s", strerror(errno));
  70. return -1;
  71. }
  72. }
  73. return 1;
  74. }