From 5ad1b22c24f97cf04c917bb22d24a0a7cabc7c71 Mon Sep 17 00:00:00 2001 From: Timo Kokkonen Date: Sun, 13 Jun 2010 19:07:14 +0300 Subject: [PATCH] main.c: Use getopt_long() for reading cmd line arguments This makes it easier to read various different command line arguments. Signed-off-by: Timo Kokkonen --- main.c | 42 ++++++++++++++++++++++++++++++++++-------- 1 file changed, 34 insertions(+), 8 deletions(-) diff --git a/main.c b/main.c index eb1b127..b42f234 100644 --- a/main.c +++ b/main.c @@ -2,6 +2,7 @@ #include #include #include +#include #include "random.h" #include "planet.h" @@ -322,6 +323,16 @@ int main(int argc, char *argv[]) int planets = 100, xres = 800, yres = 600; double total_mass = 50000; double range = 500; + int optind = 0, c; + static struct option long_options[] = { + { .val = 'x', .name = "xres", .has_arg = 1, }, + { .val = 'y', .name = "yres", .has_arg = 1, }, + { .val = 'p', .name = "planets", .has_arg = 1 }, + { .val = 'm', .name = "total-mass", .has_arg = 1 }, + { .val = 'r', .name = "range", .has_arg = 1 }, + {}, + }; + char short_options[] = "x:y:p:m:r:"; if (SDL_Init(SDL_INIT_VIDEO) != 0) { fprintf(stderr, "Unable to initialize SDL: %s\n", @@ -331,18 +342,33 @@ int main(int argc, char *argv[]) } atexit(SDL_Quit); - if (argc >= 2) - planets = atoi(argv[1]); + while (1) { + c = getopt_long(argc, argv, short_options, long_options, + &optind); + + if (c == -1) + break; - if (planets < 1) - planets = 1; + printf("%c: %s\n", c, optarg); + + switch (c) { + case 'x': + xres = atoi(optarg); + break; + case 'y': + yres = atoi(optarg); + break; - if (argc >= 3) - total_mass = atof(argv[2]); + case 'p': + planets = atoi(optarg); + break; - if (argc >= 4) - range = atof(argv[3]); + case 'r': + range = atoi(optarg); + break; + } + } screen = SDL_SetVideoMode(xres, yres, 32, flags); if (screen == NULL) { -- 2.44.0