aboutsummaryrefslogtreecommitdiff
path: root/sway/readline.c
blob: dfdc3fe87e11649080993e2f13ac29757af4405d (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
#include "readline.h"
#include <stdlib.h>
#include <stdio.h>

char *read_line(FILE *file) {
	int length = 0, size = 128;
	char *string = malloc(size);
	if (!string) {
		return NULL;
	}
	while (1) {
		int c = getc(file);
		if (c == EOF || c == '\n' || c == '\0') {
			break;
		}
		if (c == '\r') {
			continue;
		}
		if (length == size) {
			string = realloc(string, size *= 2);
			if (!string) {
				return NULL;
			}
		}
		string[length++] = c;
	}
	if (length + 1 == size) {
		string = realloc(string, length + 1);
		if (!string) {
			return NULL;
		}
	}
	string[length] = '\0';
	return string;
}