Debian Codegraph @

lib/util/io.c

raw
1 #include <assert.h>
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <errno.h>
5
6 #include "mallocvar.h"
7 #include "nstring.h"
8
9 #include "io.h"
10
11
12 void
13 pm_freadline(FILE * const fileP,
14 const char ** const lineP,
15 const char ** const errorP) {
16 /*----------------------------------------------------------------------------
17 Read a line (assuming the file is text with lines delimited by newlines)
18 from file *fileP. Return that line in newly malloced storage as *lineP.
19
20 The newline delimiter is not part of the line.
21
22 As a special case, if the file doesn't end in a newline, the characters
23 after the last newline are a line.
24
25 If there are no more lines in the file, return *lineP == NULL.
26 -----------------------------------------------------------------------------*/
27 char * buffer;
28 size_t bufferSize;
29 size_t cursor;
30 bool gotLine;
31 bool eof;
32
33 bufferSize = 1024; /* initial value */
34 *errorP = NULL; /* initial value */
35
36 MALLOCARRAY(buffer, bufferSize);
37
38 for (cursor = 0, gotLine = false, eof = false;
39 !gotLine && !eof && !*errorP; ) {
40 if (cursor + 1 >= bufferSize) {
41 if (bufferSize > INT_MAX/2) {
42 free(buffer);
43 buffer = NULL;
44 } else {
45 bufferSize *= 2;
46 REALLOCARRAY(buffer, bufferSize);
47 }
48 }
49
50 if (!buffer)
51 pm_asprintf(errorP,
52 "Couldn't get memory for a %u-byte file read buffer.",
53 (unsigned int)bufferSize);
54 else {
55 int const rc = getc(fileP);
56
57 if (rc < 0) {
58 if (feof(fileP))
59 eof = true;
60 else
61 pm_asprintf(errorP,
62 "Failed to read a character from file. "
63 "Errno = %d (%s)",
64 errno, strerror(errno));
65 } else {
66 char const c = (char)rc;
67
68 if (c == '\n')
69 gotLine = true;
70 else {
71 buffer[cursor++] = c;
72 }
73 }
74 }
75 }
76 if (*errorP) {
77 if (buffer)
78 free(buffer);
79 } else {
80 if (eof && cursor == 0) {
81 *lineP = NULL;
82 free(buffer);
83 } else {
84 assert(cursor < bufferSize);
85 buffer[cursor++] = '\0';
86
87 *lineP = buffer;
88 }
89 }
90 }
91
92