getline.c
Go to the documentation of this file.
1 #include "getline.h"
2 #include <errno.h>
3 #include <stdlib.h>
4 
5 // https://stackoverflow.com/a/47229318/8144672
6 /* The original code is public domain -- Will Hartung 4/9/09 */
7 /* Modifications, public domain as well, by Antti Haapala, 11/10/17 - Switched to getc on 5/23/19 */
8 
9 ssize_t apriltag_test_getline(char **lineptr, size_t *n, FILE *stream) {
10  size_t pos;
11  int c;
12 
13  if (lineptr == NULL || stream == NULL || n == NULL) {
14  errno = EINVAL;
15  return -1;
16  }
17 
18  c = getc(stream);
19  if (c == EOF) {
20  return -1;
21  }
22 
23  if (*lineptr == NULL) {
24  *lineptr = malloc(128);
25  if (*lineptr == NULL) {
26  return -1;
27  }
28  *n = 128;
29  }
30 
31  pos = 0;
32  while(c != EOF) {
33  if (pos + 1 >= *n) {
34  size_t new_size = *n + (*n >> 2);
35  if (new_size < 128) {
36  new_size = 128;
37  }
38  char *new_ptr = realloc(*lineptr, new_size);
39  if (new_ptr == NULL) {
40  return -1;
41  }
42  *n = new_size;
43  *lineptr = new_ptr;
44  }
45 
46  ((unsigned char *)(*lineptr))[pos ++] = c;
47  if (c == '\n') {
48  break;
49  }
50  c = getc(stream);
51  }
52 
53  (*lineptr)[pos] = '\0';
54  return pos;
55 }
getline.h
apriltag_test_getline
ssize_t apriltag_test_getline(char **lineptr, size_t *n, FILE *stream)
Definition: getline.c:9
ssize_t
intptr_t ssize_t
Definition: getline.h:7


apriltag
Author(s): Edwin Olson , Max Krogius
autogenerated on Sun Apr 20 2025 02:08:19