life.c
author Markus Bröker <mbroeker@largo.dyndns.tv>
Sat, 13 Dec 2008 17:58:16 +0100
changeset 23 7acfc5eda7ed
parent 9 c3fecc82ade6
child 27 81a574d60c15
permissions -rw-r--r--
this seems to be the proper way under ms, but it won't work under wine committer: Markus Bröker <mbroeker@largo.homelinux.org>

/**
 * test/demos/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 ("%s", 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 > 2)
        printf ("Usage: %s\n", argv[0]);

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

    return EXIT_SUCCESS;
}