diff --git a/game.c b/game.c index a4d843d..f05dd1f 100644 --- a/game.c +++ b/game.c @@ -103,17 +103,25 @@ int main(int argc, char *argv[]) copy(buf, g->grid[i]); } - free(buf); - fclose(stream); - - if (input_file) - { - nb_fruit = count_fruits(input_file, g); - } - else + rewind(stream); + nb_fruit = count_fruits(stream, g); + if (nb_fruit == 0) { + fprintf(stderr, "Error: no fruits in the grid\n"); + free(buf); + fclose(stream); exit(EXIT_FAILURE); } + if (nb_fruit == -1) + { + fprintf(stderr, "Error: unable to count fruits\n"); + free(buf); + fclose(stream); + exit(EXIT_FAILURE); + } + + free(buf); + fclose(stream); place_snake(g, &snake); diff --git a/grid.c b/grid.c index e1463f1..322f021 100644 --- a/grid.c +++ b/grid.c @@ -140,22 +140,15 @@ int count_nb_lines(FILE *stream) return count; } -int count_fruits(const char *filename, Grid *g) +int count_fruits(FILE *stream, Grid *g) { int i, j, nb_fruit = 0; - FILE *file = fopen(filename, "r"); - if (!file) - { - fprintf(stderr, "Error: Could not open file %s\n", filename); - exit(EXIT_FAILURE); - } for (i = 0; i < g->nbl; i++) { - if (!fgets(g->grid[i], g->nbc + 2, file)) + if (!fgets(g->grid[i], g->nbc + 2, stream)) { - fprintf(stderr, "Error: File %s does not contain enough lines\n", filename); - fclose(file); + fprintf(stderr, "Error: Stream does not contain enough lines\n"); exit(EXIT_FAILURE); } g->grid[i][strcspn(g->grid[i], "\n")] = '\0'; @@ -169,7 +162,6 @@ int count_fruits(const char *filename, Grid *g) } } - fclose(file); return nb_fruit; } diff --git a/grid.h b/grid.h index 8f4b07e..7208ef3 100644 --- a/grid.h +++ b/grid.h @@ -30,7 +30,7 @@ void draw_grid(Grid *g); void place_snake(Grid *g, struct SnakeStruct *snake); Element move_snake(struct SnakeStruct *snake, Grid *g); int count_nb_lines(FILE *stream); -int count_fruits(const char *filename, Grid *g); +int count_fruits(FILE *stream, Grid *g); void copy(const char *src, char *dst); #endif /* GRID_H */ \ No newline at end of file