【发布时间】:2016-05-18 09:25:26
【问题描述】:
我正在用 C 语言编写一个程序来解决迷宫游戏。输入迷宫文件将从标准输入读取。我写了下面的程序,它从标准输入读取迷宫并打印没有。行和列。但是,一旦我完全阅读了我的输入文件,我怎样才能再次访问它以便我可以执行接下来的步骤?
#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);
}
}
【问题讨论】:
-
你能改变文件的格式,以迷宫大小的两个值(宽度和高度)开头,然后是迷宫数据吗?这样,您只需对文件进行一次传递。