getl.c 2.0 KB

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