2016-05-18 78 views
3

我正在用C寫一個程序來解決迷宮遊戲。輸入迷宮文件將從標準輸入讀取。我寫了下面的程序,它從stdin讀取迷宮並打印沒有。行和列。但是,一旦我完全讀取我的輸入文件,我怎麼才能再次訪問它,以便我可以執行下一步?如何從stdin多次讀取stdin中的數據

#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); 
    } 

} 
+0

您可以更改文件的格式,以迷宮大小的兩個值(寬度和高度)開始,然後是迷宮數據?這樣,你只需要一次傳遞文件。 –

回答

5

您將不得不將它存儲在緩衝區中,因爲您閱讀它。一旦你讀到stdin,你不能倒帶它和/或再讀一遍。

+0

Angew您能幫我理解如何將數據存入緩衝區。 – user6344678

+0

我的迷宮文件就像
########
#.......#
####。####
#....#..#
#。####。##
user6344678

+0

之間沒有空間我只是直接將其轉儲到char *緩衝區中。對不起,我的C有點生鏽 –

0

如果要再次讀取文件,可以使用rewind

FILE * fp; 

// Open and read the file 

rewind(fp); 

// Read it again 

fclose(fp); 

但是,與stdin,這是行不通的。您必須存儲從stdin中讀取的內容。