aboutsummaryrefslogtreecommitdiffstats
path: root/io.c
blob: 4642285cf1b9972b38a0334fb92c6d0996204ac2 (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
/*
 * io.c
 * implementation of basic io operations
 *
 * Erik Liodden
 */

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "io.h"

/* read_lines: return an array of strings (char *) where each string is a line
 * of the input file stream fp.
 */
char **read_lines(size_t *n_lines, FILE *fp)
{
        char *line = NULL;
        size_t linecap = 0;
	size_t next = 4;
	char **lines;
        ssize_t linelen;

	*n_lines = 0;
	lines = malloc(next * sizeof(char *));
        while ((linelen = getline(&line, &linecap, fp)) > 0) {
		(*n_lines)++;
		if (*n_lines == next) {
			next *= 1.618;
			lines = realloc(lines, next * sizeof(char *));
		}
		*(lines + (*n_lines-1)) = strndup(line, linelen);
	}
	return lines;
}

/* dispose_read_lines: delete the lines created by read_lines()
 */
void dispose_read_lines(char **lines, size_t n_lines)
{
	size_t i;

	for (i = 0; i < n_lines; i++)
		free(*(lines + i));
	free(lines);
}