beta-0.89.2
[luatex.git] / source / texk / kpathsea / line.c
blob6c66a302b7f3b12e60f5cff9124f86fb7211d6df
1 /* line.c: return the next line from a file, or NULL.
3 Copyright 1992, 1993, 1995, 1996, 2008, 2013, 2014 Karl Berry.
4 Copyright 1998, 1999, 2001, 2005 Olaf Weber.
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with this library; if not, see <http://www.gnu.org/licenses/>. */
19 #include <kpathsea/config.h>
20 #include <kpathsea/line.h>
22 #ifdef WIN32
23 #undef getc
24 #undef ungetc
25 #define getc win32_getc
26 #define ungetc win32_ungetc
27 #define FLOCKFILE(x)
28 #define FUNLOCKFILE(x)
30 #else /* not WIN32 */
31 /* By POSIX, getc() has to be thread-safe, which means (un)locking on
32 every character read. It is much faster to lock the stream (once),
33 use getc_unlocked to read, and then unlock the stream. We need to be
34 thread-safe especially for the sake of MPlib.
36 Perhaps we will be lucky enough to be able to do this
37 unconditionally, without checking in configure. We'll see. */
38 #undef getc
39 #define getc getc_unlocked
40 #define FLOCKFILE(x) flockfile(x)
41 #define FUNLOCKFILE(x) funlockfile(x)
42 #endif /* not WIN32 */
44 /* Allocate in increments of this size. */
45 #define BLOCK_SIZE 75
47 char *
48 read_line (FILE *f)
50 int c;
51 unsigned limit = BLOCK_SIZE;
52 unsigned loc = 0;
53 char *line = xmalloc (limit);
55 FLOCKFILE (f);
57 while ((c = getc (f)) != EOF && c != '\n' && c != '\r') {
58 line[loc] = c;
59 loc++;
61 /* By testing after the assignment, we guarantee that we'll always
62 have space for the null we append below. We know we always
63 have room for the first char, since we start with BLOCK_SIZE. */
64 if (loc == limit) {
65 limit += BLOCK_SIZE;
66 line = xrealloc (line, limit);
70 /* If we read anything, return it, even a partial last-line-if-file
71 which is not properly terminated. */
72 if (loc == 0 && c == EOF) {
73 /* At end of file. */
74 free (line);
75 line = NULL;
76 } else {
77 /* Terminate the string. We can't represent nulls in the file,
78 but this doesn't matter. */
79 line[loc] = 0;
80 /* Absorb LF of a CRLF pair. */
81 if (c == '\r') {
82 c = getc (f);
83 if (c != '\n') {
84 ungetc (c, f);
89 FUNLOCKFILE (f);
91 return line;