diff options
Diffstat (limited to 'cmd')
-rw-r--r-- | cmd/main.c | 43 |
1 files changed, 23 insertions, 20 deletions
@@ -18,17 +18,20 @@ #define _GNU_SOURCE -#include <getopt.h> #include <errno.h> +#include <getopt.h> #include <libguile.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <unistd.h> #include "othello.h" int main(int argc, char **argv) { + int exit_status = EXIT_SUCCESS; + static const struct option long_options[] = { {"help", no_argument, NULL, 'h'}, {"player-one", required_argument, NULL, '1'}, @@ -40,8 +43,8 @@ int main(int argc, char **argv) { " -1 --player-one <file> specify a file to use for player one strategy\n" " -2 --player-two <file> specify a file to use for player two strategy\n"; - FILE *player_one_strategy = NULL; - FILE *player_two_strategy = NULL; + char *player_one_strategy_path = NULL; + char *player_two_strategy_path = NULL; int c; while (1) { @@ -56,31 +59,31 @@ int main(int argc, char **argv) { printf("%s", usage); exit(EXIT_SUCCESS); case '1': - /*char *player_one_strategy_path = strdup(optarg);*/ - if (player_one_strategy != NULL) { - fclose(player_one_strategy); - } - player_one_strategy = fopen(optarg, "r"); - if (errno != 0) { - perror("Could not open player 1 strategy"); + player_one_strategy_path = strdup(optarg); + if (access(player_one_strategy_path, F_OK) == -1) { + fprintf(stderr, "Could not access player 1 strategy\n"); + exit_status = EXIT_FAILURE; } - /*free(player_one_strategy_path);*/ break; case '2': - if (player_two_strategy != NULL) { - fclose(player_two_strategy); + player_two_strategy_path = strdup(optarg); + if (access(player_two_strategy_path, F_OK) == -1) { + fprintf(stderr, "Could not access player 2 strategy\n"); + exit_status = EXIT_FAILURE; } - player_two_strategy = fopen(optarg, "r"); - if (errno != 0) { - perror("Could not open player 2 strategy"); - } - /*char *player_two_strategy_path = strdup(optarg);*/ - /*free(player_two_strategy_path);*/ break; } } - enum player_color winner = game_loop(player_one_strategy, player_two_strategy); + // Couldn't open one or more of the player strategies, bail out. + if (exit_status == EXIT_FAILURE) { + exit(EXIT_FAILURE); + } + + enum player_color winner = + game_loop(player_one_strategy_path, player_two_strategy_path); + free(player_one_strategy_path); + free(player_two_strategy_path); switch (winner) { case WHITE: |