GRASS GIS 8 Programmer's Manual  8.5.0dev(2024)-d6dec75dd4
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 <string.h>
15 #include <stdio.h>
16 #include <grass/gis.h>
17 
18 /*!
19  * \brief Gets a line of text from a file
20  *
21  * This routine runs fgets() to fetch a line of text from a file
22  * (advancing file pointer) and removes trailing newline.
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  * \see G_getl2()
32  */
33 int G_getl(char *buf, int n, FILE *fd)
34 {
35  return G_getl2(buf, n, fd);
36 }
37 
38 /*!
39  * \brief Gets a line of text from a file of any pedigree
40  *
41  * This routine supports
42  * text files created on various platforms (UNIX, MacOS9, DOS),
43  * i.e. <code>\\n (\\012)</code>, <code>\\r (\\015)</code>, and
44  * <code>\\r\\n (\\015\\012)</code> style newlines.
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  * bytes must be allocated for the string buffer.
51  *
52  * \param buf: string buffer to receive read data, at least <i>n</i>
53  * bytes must be allocated
54  * \param n: maximum number of bytes to read
55  * \param fd: file descriptor structure
56  *
57  * \return 1 on success
58  * \return 0 EOF
59  */
60 int G_getl2(char *buf, int n, FILE *fd)
61 {
62  if (buf == NULL || fd == NULL || n <= 1) {
63  return 0;
64  }
65 
66  if (fgets(buf, n, fd) == NULL) {
67  return 0; /* EOF or error */
68  }
69 
70  /* Remove newline characters (\n, \r\n, or \r) */
71  int len = strlen(buf);
72  if (len > 0 && buf[len - 1] == '\n') {
73  buf[--len] = '\0';
74  }
75  if (len > 0 && buf[len - 1] == '\r') {
76  buf[--len] = '\0';
77  }
78 
79  return 1;
80 }
#define NULL
Definition: ccmath.h:32
int G_getl2(char *buf, int n, FILE *fd)
Gets a line of text from a file of any pedigree.
Definition: getl.c:60
int G_getl(char *buf, int n, FILE *fd)
Gets a line of text from a file.
Definition: getl.c:33