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
|
/* get_console_input.c -- function to simplify TTY input
*
* GPLv2 only - Copyright (C) 2008
* David Sommerseth <dazo@users.sourceforge.net>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <stdio.h>
#include <termios.h>
#include <string.h>
int get_console_input(char *buf, size_t len, const char *prompt, int hidden) {
struct termios term_orig, term_noecho;
char *ptr;
// Print prompt
fprintf(stdout, "%s ", prompt);
if( hidden == 1 ) {
// Get current terminal settings
if( tcgetattr(fileno(stdin), &term_orig) ) {
return -2; // Could not get the current terminal status
}
// Create a copy of current settings and turn off echo to terminal
memcpy(&term_noecho, &term_orig, sizeof(struct termios));
term_noecho.c_lflag &= ~ECHO;
if( tcsetattr(fileno(stdin), TCSAFLUSH, &term_noecho) ) {
return -3; // Could not set the new terminal settings
}
}
// Read user input from stdin
fgets(buf, len, stdin);
if( hidden == 1 ) {
// Restore terminal to saved state
tcsetattr(fileno(stdin), TCSANOW, &term_orig);
}
// Remove trailing spaces
if( buf != NULL ) {
ptr = buf + strlen(buf) - 1;
while( (ptr > buf) && ((*ptr == 0x20) || (*ptr == '\n') || (*ptr == '\r')) ) {
*ptr = 0;
ptr--;
}
ptr++;
}
if( hidden ) {
fprintf(stdout, "\n");
}
return (buf != NULL ? strlen(buf) : -1);
}
|