aboutsummaryrefslogtreecommitdiff
path: root/src/input.c
blob: ec3a766f75d7fbc606562ff13e5255a94a90a99c (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
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* stdio must be included before readline */
#include <readline/readline.h>

#include "input.h"

int prompt_yes_no(void)
{
	char *line = NULL;
	int attempts = 0;
	int ret = 0;
	do {
		line = readline(" [Y/n] ");
		char input = line[0];
		if (input == '\n'/*no input*/ || input == 'y' || input == 'Y') {
			ret = 1;
			break;
		}
		else if (input == 'n' || input == 'N') {
			break;
		}
		attempts++;
	} while(attempts < 3);
	if (line != NULL) {
		free(line);
	}
	return ret;
}

void remove_ending_newline(char *str)
{
	int idx = strlen(str) - 1;
	assert(str[idx] == '\n');
	str[idx] = '\0';
}

char *readline_with_check(const char *prompt)
{
	char *input = readline(prompt);
	if (input == NULL) {
		perror("readline");
		exit(EXIT_FAILURE);
	}
	return input;
}