gra-projekt/Implementierung/src/helper.c

88 lines
No EOL
2.1 KiB
C

#include "../lib/helper.h"
int stringToInt(char *string) {
char *leftover = "";
errno = 0;
int x = strtold(string, &leftover);
if (*leftover != '\0' || leftover == string) {
errno = EINVAL;
return -1;
}
if (errno == ERANGE) {
printf("Number is too large or too small!\n");
errno = EINVAL;
return -1;
}
errno = 0;
return x;
}
void help(char *progname) {
fprintf(
stderr,
"usage: %s [-V implementation] [-B [repetitons]] [-h] [--help] file\n",
progname);
}
enum argumentParseResult parseArguments(int argc, char **argv,
struct configuration *c) {
if (c == NULL) {
return RESULT_EXIT_FAILURE;
}
c->implementationToUse = 0;
c->doBenchmark = 0;
c->benchmarkingCycles = 1;
int opt;
while (1) {
static struct option longOptions[] = {{"help", no_argument, NULL, 'h'},
NULL};
int longOptionIndex = 0;
opt = getopt_long(argc, argv, "V:B::h", longOptions, &longOptionIndex);
if (-1 == opt) break;
switch (opt) {
case 'B':
c->doBenchmark = 1;
if (optarg != NULL) {
c->benchmarkingCycles = stringToInt(optarg);
if (errno == 0) break;
fprintf(stderr,
"%s: invalid argument, has to be int -- 'B' got '%s'\n",
argv[0], optarg);
help(argv[0]);
return RESULT_EXIT_FAILURE;
}
break;
case 'V':
c->implementationToUse = stringToInt(optarg);
if (errno == 0) break;
fprintf(stderr, "%s: invalid argument, has to be int -- 'V' got '%s'\n",
argv[0], optarg);
help(argv[0]);
return RESULT_EXIT_FAILURE;
case 'h':
help(argv[0]);
return RESULT_EXIT_SUCCESS;
default:
help(argv[0]);
return RESULT_EXIT_FAILURE;
}
}
if (argc > optind) {
c->filename = argv[optind];
} else {
fprintf(stderr, "%s: missing poisional argument -- 'file'\n", argv[0]);
help(argv[0]);
return RESULT_EXIT_FAILURE;
}
return RESULT_OK;
}