Skip to content

Commit

Permalink
Make use of getopt_long
Browse files Browse the repository at this point in the history
Simplify main.c code by using getopt_long method.

Reviewed-by: Cyril Hrubis <[email protected]>
  • Loading branch information
acerv committed Oct 11, 2023
1 parent 26941c5 commit 8b8186c
Showing 1 changed file with 41 additions and 29 deletions.
70 changes: 41 additions & 29 deletions main.c
Original file line number Diff line number Diff line change
Expand Up @@ -9,48 +9,60 @@
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "ltx.h"

int main(int argc, char *argv[])
{
int opt;
int option_index = 0;
char *serial_port = NULL;
int stdin_fd = STDIN_FILENO;
int stdout_fd = STDOUT_FILENO;;
int stdout_fd = STDOUT_FILENO;

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

const char *port = argv[2];

if (access(port, F_OK) != 0) {
printf("%s doesn't exist\n", port);
return 1;
}

stdin_fd = stdout_fd = open(port, O_RDWR | O_NOCTTY);
if (stdin_fd == -1) {
printf("Can't open %s (%s)\n", port, strerror(errno));
return 1;
}
} else if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
while ((opt = getopt_long(
argc,
argv,
"s:vh",
long_options,
&option_index)) != -1) {
switch(opt) {
case 's':
serial_port = optarg;
break;
case 'v':
printf("%s\n", VERSION);
return 0;
case 'h':
default:
printf(
"Usage: ./ltx [-h|-i|-s]\n\n"
" -i | --interactive communicate via stdin|stdout (default)\n"
"Usage: ./ltx [-s|-v|-h]\n\n"
" -s | --serial communicate via serial port\n"
" -h | --help print help message\n"
" -v | --version print version\n\n"
" -v | --version print version\n"
" -h | --help print help message\n\n"
);
return 0;
} else if (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version")) {
printf("%s\n", VERSION);
return 0;
} else {
printf("Unknown parameter: %s\n", argv[1]);
}
}

if (serial_port) {
if (access(serial_port, F_OK) != 0) {
printf("%s doesn't exist\n", serial_port);
return 1;
}

stdin_fd = stdout_fd = open(serial_port, O_RDWR | O_NOCTTY);
if (stdin_fd == -1) {
printf("Can't open %s (%s)\n", serial_port, strerror(errno));
return 1;
}
}
Expand Down

0 comments on commit 8b8186c

Please sign in to comment.