-
Notifications
You must be signed in to change notification settings - Fork 0
/
userinput.c
47 lines (41 loc) · 1.45 KB
/
userinput.c
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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
void catchSIGINT(int signo)
{
char* message = "SIGINT. Use CTRL-Z to Stop.\n";
write(STDOUT_FILENO, message, 28);
}
void main()
{
struct sigaction SIGINT_action = {0};
SIGINT_action.sa_handler = catchSIGINT;
sigfillset(&SIGINT_action.sa_mask);
//SIGINT_action.sa_flags = SA_RESTART;
sigaction(SIGINT, &SIGINT_action, NULL);
int numCharsEntered = -5; // How many chars we entered
int currChar = -5; // Tracks where we are when we print out every char
size_t bufferSize = 0; // Holds how large the allocated buffer is
char* lineEntered = NULL; // Points to a buffer allocated by getline() that holds our entered string + \n + \0
while(1)
{
// Get input from the user
while(1)
{
printf("Enter in a line of text (CTRL-C to exit):");
numCharsEntered = getline(&lineEntered, &bufferSize, stdin); // Get a line from the user
if (numCharsEntered == -1)
clearerr(stdin);
else
break; // Exit the loop - we've got input
}
printf("Allocated %zu bytes for the %d chars you entered.\n", bufferSize, numCharsEntered);
printf("Here is the raw entered line: \"%s\"\n", lineEntered);
lineEntered[strcspn(lineEntered, "\n")] = '\0'; // Remove the trailing \n that getline adds
printf("Here is the cleaned line: \"%s\"\n", lineEntered);
free(lineEntered); // Free the memory allocated by getline() or else memory leak
lineEntered = NULL;
}
}