-
Notifications
You must be signed in to change notification settings - Fork 7
/
utils.c
90 lines (70 loc) · 2 KB
/
utils.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//
// Created by Alexandra Zaharia on 10/02/19.
//
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#include "utils.h"
void error_message(char *message)
{
fprintf(stderr, "%s%s%s\n", RED, message, RESET);
}
void error_and_exit(char *message)
{
error_message(message);
exit(EXIT_FAILURE);
}
void status_message(char *message)
{
printf("%s%s%s\n", GREEN, message, RESET);
}
/*
* Removes the newline character from the buffer, if present. Also flushes STDIN.
*/
void remove_newline(char *buffer)
{
char *p = strchr(buffer, '\n');
if (p) {
*p = '\0'; // replace newline with null character
} else {
while (getchar() != '\n'); // flush STDIN
}
}
/*
* Reads at most n characters (newline included) into the buffer. If present, the newline is
* removed. Returns 0 on success and -1 on failure.
*/
int read_line(char *buffer, const int n) {
if (fgets(buffer, n, stdin) == NULL) return -1;
remove_newline(buffer);
return 0;
}
// Returns 0 if the buffer contains a valid integer, and -1 otherwise.
int _check_int(const char *buffer)
{
if (!buffer) return -1;
char *end_ptr;
long value = strtol(buffer, &end_ptr, 10);
if (end_ptr == buffer) return -1;
if (*end_ptr != '\0') return -1; // buffer ends with non-digit characters
if ((value == LONG_MIN || value == LONG_MAX) && errno != 0) return -1;
if (value < INT_MIN || value > INT_MAX) return -1;
return 0;
}
// Attempts to read an integer into n from the buffer. Returns 0 on success and -1 on failure.
int read_int_from_buffer(const char *buffer, int *n)
{
if (_check_int(buffer) == -1) return -1;
*n = (int) strtol(buffer, NULL, 10);
return 0;
}
// Attempts to read an integer into n from STDIN. Returns 0 on success and -1 on failure.
int read_int_from_stdin(int *n)
{
char buffer[12];
if (read_line(buffer, 12) == -1 || _check_int(buffer) == -1) return -1;
*n = (int) strtol(buffer, NULL, 10);
return 0;
}