-
Notifications
You must be signed in to change notification settings - Fork 1
/
args.c
104 lines (82 loc) · 2.14 KB
/
args.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/* All Rights Reversed - No Rights Reserved */
#include "args.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define PROGRAM_NAME "fast-grep"
#define PROGRAM_VERSION "0.1"
#define PROGRAM_NAME_VERSION PROGRAM_NAME "-" PROGRAM_VERSION
/* Filled in by parse_args */
struct opts opt;
/* Program documentation. */
static char *prog_doc =
PROGRAM_NAME_VERSION
"\nFast, multi-threaded grep.\n\n"
"USAGE\n\n" PROGRAM_NAME
" [OPTIONS] "
"<needle> <haystack>\n\n"
"MANDATORY ARGUMENTS\n\n"
"needle - string to search for\n"
"haystack - name of file to search (for needle string)\n\n"
"OPTIONS\n\n"
"-v <invert> - skip lines containing the \"invert\" pattern\n"
"-s - single-thread (disable multi-threading)\n"
"-d - print some debug info during execution\n"
"-h - print this help text\n\n"
"EXAMPLE\n\n"
"Print all lines in the file cred containing the string\n"
"'.se-', but skip lines containing the string '-|-|--':\n\n"
"./" PROGRAM_NAME " -v '-|-|--' '.se-' cred\n\n";
void print_usage(void)
{
printf("%s", prog_doc);
}
int parse_args(int argc, char **argv)
{
int c;
/* Default values. */
opt.vstring = NULL;
opt.single = 0;
opt.debug = 0;
/* Parse optional arguments */
opterr = 0;
while ((c = getopt (argc, argv, "hsdv:")) != -1) {
switch (c) {
case 'v':
opt.vstring = optarg;
opt.vlen = strlen(opt.vstring);
break;
case 's':
opt.single = 1;
break;
case 'd':
opt.debug = 1;
break;
case 'h':
/* Just print help text */
return 0;
case '?':
fprintf(stderr, "Error: unknown option -%c\n\n", optopt);
return 0;
default:
return 0;
}
}
if (argc != optind + 2) {
puts("Error: wrong number of mandatory arguments");
return 0;
}
/* Mandatory arguments */
opt.needle = argv[optind++];
opt.needlen = strlen(opt.needle);
opt.filename = argv[optind];
return 1;
}
/**
* Local Variables:
* mode: c
* indent-tabs-mode: nil
* c-basic-offset: 3
* End:
*/