Skip to content

Instantly share code, notes, and snippets.

@zorawar87
Created February 11, 2018 01:00
Show Gist options
  • Save zorawar87/84776635627e0322eabb02c1d56fcbb3 to your computer and use it in GitHub Desktop.
Save zorawar87/84776635627e0322eabb02c1d56fcbb3 to your computer and use it in GitHub Desktop.
Handling Command Line Args in C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
//#include <curl/curl.h>
#define URL_BASE "http://someurl.cc/"
#define URL_1M URL_BASE "file_1M.bin"
#define URL_2M URL_BASE "file_2M.bin"
#define URL_5M URL_BASE "file_5M.bin"
#define URL_10M URL_BASE "file_10M.bin"
#define URL_20M URL_BASE "file_20M.bin"
#define URL_50M URL_BASE "file_50M.bin"
#define URL_100M URL_BASE "file_100M.bin"
#define CHKSPEED_VERSION "1.0"
int main(int argc, char **argv){
int prtall = 0, prtsep = 0, prttime = 0;
const char *url = URL_1M;
char *appname = argv[0];
if(argc > 1) {
/* parse input parameters */
for(argc--, argv++; *argv; argc--, argv++) {
if(strncasecmp(*argv, "-", 1) == 0) {
if(strncasecmp(*argv, "-H", 2) == 0) {
fprintf(stderr,
"\rUsage: %s [-m=1|2|5|10|20|50|100] [-t] [-x] [url]\n",
appname);
exit(1);
}
else if(strncasecmp(*argv, "-V", 2) == 0) {
fprintf(stderr, "\r%s %s - %s\n",
appname, CHKSPEED_VERSION, "curl_version");
exit(1);
}
else if(strncasecmp(*argv, "-A", 2) == 0) {
prtall = 1;
}
else if(strncasecmp(*argv, "-A", 2) == 0) {
prtall = 1;
}
else if(strncasecmp(*argv, "-X", 2) == 0) {
prtsep = 1;
}
else if(strncasecmp(*argv, "-T", 2) == 0) {
prttime = 1;
}
else if(strncasecmp(*argv, "-M=", 3) == 0) {
long m = strtol((*argv) + 3, NULL, 10);
switch(m) {
case 1:
url = URL_1M;
break;
case 2:
url = URL_2M;
break;
case 5:
url = URL_5M;
break;
case 10:
url = URL_10M;
break;
case 20:
url = URL_20M;
break;
case 50:
url = URL_50M;
break;
case 100:
url = URL_100M;
break;
default:
fprintf(stderr, "\r%s: invalid parameter %s\n",
appname, *argv + 3);
exit(1);
}
}
else {
fprintf(stderr, "\r%s: invalid or unknown option %s\n",
appname, *argv);
exit(1);
}
}
else {
url = *argv;
}
}
}
/* print separator line */
if(prtsep) {
printf("-------------------------------------------------\n");
}
/* print localtime */
if(prttime) {
time_t t = time(NULL);
printf("Localtime: %s", ctime(&t));
}
//CURL stuff follows
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment