From 28c9a690055cd879df1bf744e01b056d1d992ccb Mon Sep 17 00:00:00 2001 From: Thomas Wade Date: Thu, 1 Nov 2018 10:23:59 +1030 Subject: [PATCH] Replace arg parsing with getopt --- server1.c | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/server1.c b/server1.c index 75c49fd..da477c2 100644 --- a/server1.c +++ b/server1.c @@ -10,10 +10,12 @@ #include #include #include +#include #define BUFFERT 512 #define BACKLOG 1 +void usage(char* programName); int create_server_socket(int port); struct sockaddr_in sock_serv, sock_clt; @@ -29,12 +31,31 @@ int main(int argc, char** argv) time_t intps; struct tm* tmi; - /* (A) repalce the following line with suitable getopt() functionality */ - if (argc != 2) + // Parse options + char argchar; + while ((argchar = getopt(argc, argv, "")) != -1) { - perror("Usage ./a.out \n"); + switch (argchar) + { + default: + break; + } + } + + // Parse positional arguments + int port; + char* file_path; + if (argv[optind] == NULL || argv[optind + 1] == NULL) + { + usage(argv[0]); exit(3); } + else + { + port = atoi(argv[optind]); + file_path = argv[optind + 1]; + } + int l; int yes = 1; @@ -154,3 +175,8 @@ int main(int argc, char** argv) return EXIT_SUCCESS; } + +void usage(char* programName) +{ + fprintf(stderr, "Usage: %s [OPTIONS] \n", programName); +}