init.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /****************************************************************************
  2. *
  3. * MODULE: segment
  4. * AUTHOR(S): CERL
  5. * Bernhard Reiter <bernhard intevation.de>,
  6. * Brad Douglas <rez touchofmadness.com>,
  7. * Glynn Clements <glynn gclements.plus.com>,
  8. * Markus Neteler <neteler itc.it>
  9. * PURPOSE: Segment initialization routines
  10. * COPYRIGHT: (C) 2000-2006 by the GRASS Development Team
  11. *
  12. * This program is free software under the GNU General Public
  13. * License (>=v2). Read the file COPYING that comes with GRASS
  14. * for details.
  15. *
  16. *****************************************************************************/
  17. #include <stdio.h>
  18. #include <unistd.h>
  19. #include <string.h>
  20. #include <errno.h>
  21. #include <grass/segment.h>
  22. static int read_int(int, int *);
  23. /* fd must be open for read and write */
  24. /**
  25. * \fn int segment_init (SEGMENT *SEG, int fd, int nseg)
  26. *
  27. * \brief Initialize segment structure.
  28. *
  29. * Initializes the <b>seg</b> structure. The file on <b>fd</b> is
  30. * a segment file created by <i>segment_format()</i> and must be open
  31. * for reading and writing. The segment file configuration parameters
  32. * <i>nrows, ncols, srows, scols</i>, and <i>len</i>, as written to the
  33. * file by <i>segment_format()</i>, are read from the file and stored in
  34. * the <b>seg</b> structure. <b>nsegs</b> specifies the number of
  35. * segments that will be retained in memory. The minimum value allowed
  36. * is 1.
  37. *
  38. * <b>Note:</b> The size of a segment is <em>scols*srows*len</em> plus a
  39. * few bytes for managing each segment.
  40. *
  41. * \param[in,out] seg segment
  42. * \param[in] fd file descriptor
  43. * \param[in] nsegs number of segments to remain in memory
  44. * \return 1 if successful
  45. * \return -1 if unable to seek or read segment file
  46. * \return -2 if out of memory
  47. */
  48. int segment_init(SEGMENT * SEG, int fd, int nseg)
  49. {
  50. SEG->open = 0;
  51. SEG->fd = fd;
  52. SEG->nseg = nseg;
  53. if (lseek(fd, 0L, SEEK_SET) < 0) {
  54. G_warning("segment_init: %s", strerror(errno));
  55. return -1;
  56. }
  57. /* read the header */
  58. if (!read_int(fd, &SEG->nrows)
  59. || !read_int(fd, &SEG->ncols)
  60. || !read_int(fd, &SEG->srows)
  61. || !read_int(fd, &SEG->scols)
  62. || !read_int(fd, &SEG->len))
  63. return -1;
  64. return segment_setup(SEG);
  65. }
  66. static int read_int(int fd, int *n)
  67. {
  68. int bytes_read;
  69. if ((bytes_read = read(fd, n, sizeof(int))) == -1)
  70. G_warning("read_int: %s", strerror(errno));
  71. bytes_read = (bytes_read == sizeof(int));
  72. return bytes_read;
  73. }