GRASS GIS 8 Programmer's Manual  8.4.0dev(2024)-2653d7b383
getl.c
Go to the documentation of this file.
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 
14 #include <stdio.h>
15 #include <grass/gis.h>
16 
17 /*!
18  * \brief Gets a line of text from a file
19  *
20  * This routine runs fgets() to fetch a line of text from a file
21  * (advancing file pointer) and removes trailing newline. fgets() does
22  * not recognize '<code>\\r</code>' as an EOL and will read past * it.
23  *
24  * \param buf string buffer to receive read data
25  * \param n maximum number of bytes to read
26  * \param fd file descriptor structure
27  *
28  * \return 1 on success
29  * \return 0 EOF
30  */
31 int G_getl(char *buf, int n, FILE *fd)
32 {
33  if (!fgets(buf, n, fd))
34  return 0;
35 
36  for (; *buf && *buf != '\n'; buf++)
37  ;
38  *buf = 0;
39 
40  return 1;
41 }
42 
43 /*!
44  * \brief Gets a line of text from a file of any pedigree
45  *
46  * This routine is like G_getl() but is more portable. It supports
47  * text files created on various platforms (UNIX, MacOS9, DOS),
48  * i.e. <code>\\n (\\012)</code>, <code>\\r (\\015)</code>, and
49  * <code>\\r\\n (\\015\\012)</code> style newlines.
50  *
51  *
52  * Reads in at most <i>n-1</i> characters from stream (the last spot
53  * is reserved for the end-of-string NUL) and stores them into the
54  * buffer pointed to by <i>buf</i>. Reading stops after an EOF or a
55  * newline. New line is not stored in the buffer. At least <i>n</i>
56  * must be allocated for the string buffer.
57  *
58  * \param buf: string buffer to receive read data, at least <i>n</i> must be
59  * allocated \param n: maximum number of bytes to read \param fd: file
60  * descriptor structure
61  *
62  * \return 1 on success
63  * \return 0 EOF
64  */
65 int G_getl2(char *buf, int n, FILE *fd)
66 {
67  int i = 0;
68  int c;
69  int ret = 1;
70 
71  while (i < n - 1) {
72  c = fgetc(fd);
73 
74  if (c == EOF) {
75  if (i == 0) { /* Read correctly (return 1) last line in file without
76  '\n' */
77  ret = 0;
78  }
79  break;
80  }
81 
82  if (c == '\n')
83  break; /* UNIX */
84 
85  if (c == '\r') { /* DOS or MacOS9 */
86  if ((c = fgetc(fd)) != EOF) {
87  if (c !=
88  '\n') { /* MacOS9 - we have to return the char to stream */
89  ungetc(c, fd);
90  }
91  }
92  break;
93  }
94 
95  buf[i] = c;
96 
97  i++;
98  }
99  buf[i] = '\0';
100 
101  return ret;
102 }
int G_getl2(char *buf, int n, FILE *fd)
Gets a line of text from a file of any pedigree.
Definition: getl.c:65
int G_getl(char *buf, int n, FILE *fd)
Gets a line of text from a file.
Definition: getl.c:31