life.c
author Markus Bröker<broeker.markus@googlemail.com>
Fri, 20 Oct 2017 06:43:33 +0200
changeset 169 df7c720bcaa6
parent 152 53ca9bff8b40
permissions -rw-r--r--
Service Pack 1 for a software from 2008 :gg

/**
 * life.c
 * Copyright (C) 2008 Markus Broeker
 */

#include <stdio.h>
#include <stdlib.h>

#define MAX 12

int read_file (char **);
int init_life (char **);
void free_life (char **);
void show_life (char **);

int read_file (char **arena)
{
    int i, j;

    char org;
    char file[80];

    FILE *inp = NULL;

    while (inp == NULL) {
        printf ("Please enter the file name>> ");
        if (scanf ("%80s", file) < 1)
            return -1;

        inp = fopen (file, "r");
    }

    for (i = 0; i < MAX; i++) {
        printf ("Reading Line %3d: ", i);
        for (j = 0; j < MAX; j++) {
            if (feof (inp)) {
                printf ("EOF detected\n");
                return fclose (inp);
            }

            if ((fscanf (inp, "%c ", &org)) < 1)
                return -1;

            arena[i][j] = org;
            printf ("%c ", arena[i][j]);
        }
        printf ("\n");
    }

    return fclose (inp);
}

int init_life (char **arena)
{
    int i, j;

    for (i = 0; i < MAX; i++) {
        if ((arena[i] = malloc (MAX + 1)) == NULL)
            return -1;
        for (j = 0; j < MAX; j++)
            arena[i][j] = '.';
    }

    for (i = 0; i < MAX; i++) {
        arena[0][i] = '-';
        arena[MAX - 1][i] = '-';
        arena[i][0] = '|';
        arena[i][MAX - 1] = '|';
        printf ("Initialize: %d\n", i);
    }

    if ((read_file (arena) == EOF)) {
        printf ("\nread_file: ERROR\n");
        return -1;
    }

    return 0;
}

void show_life (char **arena)
{
    int i, j;

    for (i = 0; i < MAX; i++) {
        for (j = 0; j < MAX; j++) {
            printf ("%c", arena[i][j]);
        }
        printf ("\n");
    }
}

void free_life (char **arena)
{
    int i;

    if (arena == NULL)
        return;

    for (i = 0; i < MAX; i++) {
        if (arena[i] != NULL)
            free (arena[i]);
    }

}

int main (int argc, char **argv)
{
    char *arena[MAX];

    if (argc > 1)
        printf ("Usage: %s\n", argv[0]);

    if (init_life (arena) == 0)
        show_life (arena);
    free_life (arena);

    return EXIT_SUCCESS;
}