GRASS GIS 8 Programmer's Manual  8.5.0dev(2024)-b082d422ef
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. fgets() does
23  * not recognize '<code>\\r</code>' as an EOL and will read past * it.
24  *
25  * \param buf string buffer to receive read data
26  * \param n maximum number of bytes to read
27  * \param fd file descriptor structure
28  *
29  * \return 1 on success
30  * \return 0 EOF
31  */
32 int G_getl(char *buf, int n, FILE *fd)
33 {
34  if (!fgets(buf, n, fd))
35  return 0;
36 
37  for (; *buf && *buf != '\n'; buf++)
38  ;
39  *buf = 0;
40 
41  return 1;
42 }
43 
44 /*!
45  * \brief Gets a line of text from a file of any pedigree
46  *
47  * This routine is like G_getl() but is more portable. It supports
48  * text files created on various platforms (UNIX, MacOS9, DOS),
49  * i.e. <code>\\n (\\012)</code>, <code>\\r (\\015)</code>, and
50  * <code>\\r\\n (\\015\\012)</code> style newlines.
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  * bytes must be allocated for the string buffer.
57  *
58  * \param buf: string buffer to receive read data, at least <i>n</i>
59  * bytes must be allocated
60  * \param n: maximum number of bytes to read
61  * \param fd: file descriptor structure
62  *
63  * \return 1 on success
64  * \return 0 EOF
65  */
66 int G_getl2(char *buf, int n, FILE *fd)
67 {
68  if (buf == NULL || fd == NULL || n <= 1) {
69  return 0;
70  }
71 
72  if (fgets(buf, n, fd) == NULL) {
73  return 0; /* EOF or error */
74  }
75 
76  /* Remove newline characters (\n, \r\n, or \r) */
77  int len = strlen(buf);
78  if (len > 0 && buf[len - 1] == '\n') {
79  buf[--len] = '\0';
80  }
81  if (len > 0 && buf[len - 1] == '\r') {
82  buf[--len] = '\0';
83  }
84 
85  return 1;
86 }
#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:66
int G_getl(char *buf, int n, FILE *fd)
Gets a line of text from a file.
Definition: getl.c:32