Improving count fruit function
This commit is contained in:
24
game.c
24
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);
|
||||
|
||||
|
||||
14
grid.c
14
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;
|
||||
}
|
||||
|
||||
|
||||
2
grid.h
2
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 */
|
||||
Reference in New Issue
Block a user