summaryrefslogtreecommitdiff
path: root/cmd-line-utils/libedit/fgetln.c
blob: 4f7416a4c8da174e014f1991f0dd32fec1971b48 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <stdio.h>
#include "compat.h"

#ifndef HAVE_FGETLN

#ifdef HAVE_GETLINE

extern int getline (char **lineptr, size_t *n, FILE *stream);

#else

/* The interface here is that of GNU libc's getline */
static int
getline (char **lineptr, size_t *n, FILE *stream)
{
#define EXPAND_CHUNK 16

  int n_read = 0;
  char *line = *lineptr;

  if (lineptr == NULL) return -1;
  if (n == NULL) return -1;
  if (stream == NULL) return -1;
  if (*lineptr == NULL || *n == 0) return -1;
  
#ifdef HAVE_FLOCKFILE
  flockfile (stream);
#endif  
  
  while (1)
    {
      int c;
      
#ifdef HAVE_FLOCKFILE
      c = getc_unlocked (stream);
#else
      c = getc (stream);
#endif      

      if (c == EOF)
        {
          if (n_read > 0)
	    line[n_read] = '\0';
          break;
        }

      if (n_read + 2 >= *n)
        {
	  size_t new_size;

	  if (*n == 0)
	    new_size = 16;
	  else
	    new_size = *n * 2;

	  if (*n >= new_size)    /* Overflowed size_t */
	    line = NULL;
	  else
	    line = (char *) (*lineptr ? (char*) realloc(*lineptr, new_size) :
			     (char*) malloc(new_size));

	  if (line)
	    {
	      *lineptr = line;
	      *n = new_size;
	    }
	  else
	    {
	      if (*n > 0)
		{
		  (*lineptr)[*n - 1] = '\0';
		  n_read = *n - 2;
		}
	      break;
	    }
        }

      line[n_read] = c;
      n_read++;

      if (c == '\n')
        {
          line[n_read] = '\0';
          break;
        }
    }

#ifdef HAVE_FLOCKFILE
  funlockfile (stream);
#endif

  return n_read - 1;
}
#endif /* ! HAVE_GETLINE */

char *fgetln(FILE *stream, size_t *len)
{
  char *ptr = NULL;
  int sz;
  size_t length= 0;

  sz = getline(&ptr,  &length, stream);
  if(len) {
    *len = sz;
  }

  return sz >= 0 ? ptr : NULL;
}
#endif