getl.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*!
  2. * \file lib/gis/getl.c
  3. *
  4. * \brief GIS Library - Get line of text from file
  5. *
  6. * (C) 2001-2009 by the GRASS Development Team
  7. *
  8. * This program is free software under the GNU General Public License
  9. * (>=v2). Read the file COPYING that comes with GRASS for details.
  10. *
  11. * \author Original author CERL
  12. */
  13. #include <stdio.h>
  14. #include <grass/gis.h>
  15. /*!
  16. * \brief Gets a line of text from a file
  17. *
  18. * This routine runs fgets() to fetch a line of text from a file
  19. * (advancing file pointer) and removes trailing newline. fgets() does
  20. * not recognize '<code>\\r</code>' as an EOL and will read past * it.
  21. *
  22. * \param buf string buffer to receive read data
  23. * \param n maximum number of bytes to read
  24. * \param fd file descriptor structure
  25. *
  26. * \return 1 on success
  27. * \return 0 EOF
  28. */
  29. int G_getl(char *buf, int n, FILE * fd)
  30. {
  31. if (!fgets(buf, n, fd))
  32. return 0;
  33. for (; *buf && *buf != '\n'; buf++) ;
  34. *buf = 0;
  35. return 1;
  36. }
  37. /*!
  38. * \brief Gets a line of text from a file of any pedigree
  39. *
  40. * This routine is like G_getl() but is more portable. It supports
  41. * text files created on various platforms (UNIX, MacOS9, DOS),
  42. * i.e. <code>\\n (\\012)</code>, <code>\\r (\\015)</code>, and
  43. * <code>\\r\\n (\\015\\012)</code> style newlines.
  44. *
  45. *
  46. * Reads in at most <i>n-1</i> characters from stream (the last spot
  47. * is reserved for the end-of-string NUL) and stores them into the
  48. * buffer pointed to by <i>buf</i>. Reading stops after an EOF or a
  49. * newline. New line is not stored in the buffer. At least <i>n</i>
  50. * must be allocated for the string buffer.
  51. *
  52. * \param buf: string buffer to receive read data, at least <i>n</i> must be allocated
  53. * \param n: maximum number of bytes to read
  54. * \param fd: file descriptor structure
  55. *
  56. * \return 1 on success
  57. * \return 0 EOF
  58. */
  59. int G_getl2(char *buf, int n, FILE * fd)
  60. {
  61. int i = 0;
  62. int c;
  63. int ret = 1;
  64. while (i < n - 1) {
  65. c = fgetc(fd);
  66. if (c == EOF) {
  67. if (i == 0) { /* Read correctly (return 1) last line in file without '\n' */
  68. ret = 0;
  69. }
  70. break;
  71. }
  72. if (c == '\n')
  73. break; /* UNIX */
  74. if (c == '\r') { /* DOS or MacOS9 */
  75. if ((c = fgetc(fd)) != EOF) {
  76. if (c != '\n') { /* MacOS9 - we have to return the char to stream */
  77. ungetc(c, fd);
  78. }
  79. }
  80. break;
  81. }
  82. buf[i] = c;
  83. i++;
  84. }
  85. buf[i] = '\0';
  86. return ret;
  87. }