Skip to content

Commit 8b8186c

Browse files
committed
Make use of getopt_long
Simplify main.c code by using getopt_long method. Reviewed-by: Cyril Hrubis <chrubis@suse.cz>
1 parent 26941c5 commit 8b8186c

1 file changed

Lines changed: 41 additions & 29 deletions

File tree

main.c

Lines changed: 41 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -9,48 +9,60 @@
99
#include <errno.h>
1010
#include <string.h>
1111
#include <unistd.h>
12+
#include <getopt.h>
1213
#include <sys/stat.h>
1314
#include <sys/types.h>
1415
#include "ltx.h"
1516

1617
int main(int argc, char *argv[])
1718
{
19+
int opt;
20+
int option_index = 0;
21+
char *serial_port = NULL;
1822
int stdin_fd = STDIN_FILENO;
19-
int stdout_fd = STDOUT_FILENO;;
23+
int stdout_fd = STDOUT_FILENO;
2024

21-
if (argc >= 2 && strcmp(argv[1], "-i") && strcmp(argv[1], "--interactive")) {
22-
if (!strcmp(argv[1], "-s") || !strcmp(argv[1], "--serial")) {
23-
if (argc != 3) {
24-
printf("Serial port is not defined\n");
25-
return 1;
26-
}
25+
static struct option long_options[] = {
26+
{"serial", required_argument, NULL, 's'},
27+
{"version", no_argument, NULL, 'v'},
28+
{"help", no_argument, NULL, 'h'},
29+
{0, 0, 0, 0}
30+
};
2731

28-
const char *port = argv[2];
29-
30-
if (access(port, F_OK) != 0) {
31-
printf("%s doesn't exist\n", port);
32-
return 1;
33-
}
34-
35-
stdin_fd = stdout_fd = open(port, O_RDWR | O_NOCTTY);
36-
if (stdin_fd == -1) {
37-
printf("Can't open %s (%s)\n", port, strerror(errno));
38-
return 1;
39-
}
40-
} else if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
32+
while ((opt = getopt_long(
33+
argc,
34+
argv,
35+
"s:vh",
36+
long_options,
37+
&option_index)) != -1) {
38+
switch(opt) {
39+
case 's':
40+
serial_port = optarg;
41+
break;
42+
case 'v':
43+
printf("%s\n", VERSION);
44+
return 0;
45+
case 'h':
46+
default:
4147
printf(
42-
"Usage: ./ltx [-h|-i|-s]\n\n"
43-
" -i | --interactive communicate via stdin|stdout (default)\n"
48+
"Usage: ./ltx [-s|-v|-h]\n\n"
4449
" -s | --serial communicate via serial port\n"
45-
" -h | --help print help message\n"
46-
" -v | --version print version\n\n"
50+
" -v | --version print version\n"
51+
" -h | --help print help message\n\n"
4752
);
4853
return 0;
49-
} else if (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version")) {
50-
printf("%s\n", VERSION);
51-
return 0;
52-
} else {
53-
printf("Unknown parameter: %s\n", argv[1]);
54+
}
55+
}
56+
57+
if (serial_port) {
58+
if (access(serial_port, F_OK) != 0) {
59+
printf("%s doesn't exist\n", serial_port);
60+
return 1;
61+
}
62+
63+
stdin_fd = stdout_fd = open(serial_port, O_RDWR | O_NOCTTY);
64+
if (stdin_fd == -1) {
65+
printf("Can't open %s (%s)\n", serial_port, strerror(errno));
5466
return 1;
5567
}
5668
}

0 commit comments

Comments
 (0)