File: getln.c

package info (click to toggle)
shell-fm 0.7%2Bgit20100414-2
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 444 kB
  • ctags: 305
  • sloc: ansic: 4,422; makefile: 135; python: 80; haskell: 76; sh: 67; perl: 19
file content (53 lines) | stat: -rw-r--r-- 1,294 bytes parent folder | download | duplicates (2)
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
/*
	Copyright (C) 2006 by Jonas Kramer
	Published under the terms of the GNU General Public License (GPL).
*/


#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#include "getln.h"

/*
	Reads a line until EOF or a line break occurs, whatever comes first.
	The first parameter must be a pointer to another pointer which should either
	be NULL or point to memory area reserved with *alloc. If it's a pointer to a
	memory area, that memory will be used and resized as needed. In this case,
	the second argument must point to an unsigned holding the size of the
	allocated memory area. Otherwise, the memory will be freshly allocated and
	it's size will be stored in the unsigned pointed to by the second argument.
	The third argument is a FILE pointer which the line will be read from.
*/
unsigned getln(char ** ptr, unsigned * size, FILE * fd) {
	unsigned length = 0;
	int ch = 0;

	assert(size != NULL);

	if(!(* ptr))
		* size = 0;
	
	while(!feof(fd) && ch != (char) 10) {
		ch = fgetc(fd);

		if(ch == -1)
			ch = 0;
		
		if(length + 2 > * size) {
			* ptr = realloc(* ptr, (* size += 1024));
			assert(* ptr != NULL);
		}

		(* ptr)[length++] = (char) ch;
		(* ptr)[length] = 0;
	}

	* size = length + 1;
	* ptr = realloc(* ptr, * size);

	assert(* ptr != NULL);

	return length;
}