4

I am writing a program in C to solve a maze game. The input maze file will be read from stdin. I have written below program which read the maze from stdin and prints no. of rows and columns. But once I read my input file completely how can I access it again so that I can perform the next steps?

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

#define BUFFERSIZE (1000)


struct maze {
    char ** map;
    int startx, starty;
    int numrows;
    int initdir;
};

void ReadMaze(char * filename, struct maze * maze);

int main(int argc, char *argv[]) {
    struct maze maze;


    ReadMaze(argv[1], &maze);

    return EXIT_SUCCESS;
}


/*  Creates a maze from a file  */

void ReadMaze(char * filename, struct maze * maze) {
    char buffer[BUFFERSIZE];
    char mazeValue [BUFFERSIZE][BUFFERSIZE];
    char ** map;
    int rows = 0, foundentrance = 0, foundexit = 0;
    int columns = 0;

    /*  Determine number of rows in maze  */


    while ( fgets(buffer, BUFFERSIZE, stdin) ){
       ++rows;
       puts(buffer);
       columns = strlen(buffer);

    }

    printf("No of rows:  %d\n", rows);
    printf("No of columns: %d\n", columns);

    if ( !(map = malloc(rows * sizeof *map)) ) {
        fputs("Couldn't allocate memory for map\n", stderr);
        exit(EXIT_FAILURE);
    }

}
  • Can you change the format of the file to start with two values (width and height) for the size of the maze, followed by the maze data ? That way, you only need one pass on the file. – Sander De Dycker May 18 '16 at 09:33

2 Answers2

5

You're going to have to store that in a buffer as you read it. Once you've read stdin, you can't rewind it and/or read it again.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
0

If you want to read a file again, rewind can be used.

FILE * fp;

// Open and read the file

rewind(fp);

// Read it again

fclose(fp);

But, with stdin, this doesn't work. You must store the contents read from stdin.

Shreevardhan
  • 12,233
  • 3
  • 36
  • 50