This repository has been archived by the owner on Mar 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
strcmp.c
83 lines (74 loc) · 1.87 KB
/
strcmp.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
/* getopt */
#include <unistd.h>
#include <stdio.h>
/* EXIT_FAILURE */
#include <stdlib.h>
/* strcmp */
#include <string.h>
/* bool */
#include <stdbool.h>
/* isspace */
#include <ctype.h>
static void print_usage(FILE *, char *);
static int strcmp_ignore_spaces(const unsigned char *restrict, const unsigned char *restrict);
int main(int argc, char *argv[])
{
int opt = 0;
bool ignore_spaces = false;
while ((opt = getopt(argc, argv, "hw")) != -1) {
switch (opt) {
case 'w':
ignore_spaces = true;
break;
case 'h':
print_usage(stdout, argv[0]);
return EXIT_SUCCESS;
default: /* '?' */
print_usage(stderr,argv[0]);
return EXIT_FAILURE;
}
}
/* Either 1 (prog name) + 2 (num of args) = 3,
* or 1 (prog name) + 3 (num of args) = 4
*/
if ((!ignore_spaces && 3 != argc) || (ignore_spaces && 4 != argc)) {
fputs("ERROR: wrong usage\n", stderr);
print_usage(stderr, argv[0]);
return EXIT_FAILURE;
}
if ((!ignore_spaces && !strcmp(argv[optind], argv[optind + 1]))
|| (ignore_spaces
&& !strcmp_ignore_spaces(
(const unsigned char *restrict) argv[optind],
(const unsigned char *restrict) argv[optind + 1]))) {
puts("true");
} else {
puts("false");
}
return EXIT_SUCCESS;
}
static void print_usage(FILE *stream,char *prog_name)
{
fprintf(stream,
"Usage: %s [OPTIONS] [STRING_1] [STRING_2]\n"
"Compare between two strings. Prints 'true' if they are the same, otherwise prints 'false'.\n"
"\n"
"OPTIONS:\n"
" -h Print this help message and exit\n"
" -w Ignore whitespaces when comparing the string\n",
prog_name);
}
static int strcmp_ignore_spaces(
const unsigned char *restrict str1,
const unsigned char *restrict str2)
{
do {
while (isspace(*str1)) {
++str1;
}
while (isspace(*str2)) {
++str2;
}
} while (*str1 && (*str1++ == *str2++));
return *str1 - *str2;
}